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-2023, 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/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"
35 #include "pgstat.h"
38 #include "replication/origin.h"
39 #include "replication/slot.h"
41 #include "replication/walsender.h"
43 #include "storage/lmgr.h"
44 #include "utils/acl.h"
45 #include "utils/builtins.h"
46 #include "utils/guc.h"
47 #include "utils/lsyscache.h"
48 #include "utils/memutils.h"
49 #include "utils/pg_lsn.h"
50 #include "utils/syscache.h"
51 
52 /*
53  * Options that can be specified by the user in CREATE/ALTER SUBSCRIPTION
54  * command.
55  */
56 #define SUBOPT_CONNECT 0x00000001
57 #define SUBOPT_ENABLED 0x00000002
58 #define SUBOPT_CREATE_SLOT 0x00000004
59 #define SUBOPT_SLOT_NAME 0x00000008
60 #define SUBOPT_COPY_DATA 0x00000010
61 #define SUBOPT_SYNCHRONOUS_COMMIT 0x00000020
62 #define SUBOPT_REFRESH 0x00000040
63 #define SUBOPT_BINARY 0x00000080
64 #define SUBOPT_STREAMING 0x00000100
65 #define SUBOPT_TWOPHASE_COMMIT 0x00000200
66 #define SUBOPT_DISABLE_ON_ERR 0x00000400
67 #define SUBOPT_LSN 0x00000800
68 #define SUBOPT_ORIGIN 0x00001000
69 
70 /* check if the 'val' has 'bits' set */
71 #define IsSet(val, bits) (((val) & (bits)) == (bits))
72 
73 /*
74  * Structure to hold a bitmap representing the user-provided CREATE/ALTER
75  * SUBSCRIPTION command options and the parsed/default values of each of them.
76  */
77 typedef struct SubOpts
78 {
80  char *slot_name;
82  bool connect;
83  bool enabled;
85  bool copy_data;
86  bool refresh;
87  bool binary;
88  char streaming;
89  bool twophase;
91  char *origin;
94 
95 static List *fetch_table_list(WalReceiverConn *wrconn, List *publications);
97  List *publications, bool copydata,
98  char *origin, Oid *subrel_local_oids,
99  int subrel_count, char *subname);
100 static void check_duplicates_in_publist(List *publist, Datum *datums);
101 static List *merge_publications(List *oldpublist, List *newpublist, bool addpub, const char *subname);
102 static void ReportSlotConnectionError(List *rstates, Oid subid, char *slotname, char *err);
103 
104 
105 /*
106  * Common option parsing function for CREATE and ALTER SUBSCRIPTION commands.
107  *
108  * Since not all options can be specified in both commands, this function
109  * will report an error if mutually exclusive options are specified.
110  */
111 static void
113  bits32 supported_opts, SubOpts *opts)
114 {
115  ListCell *lc;
116 
117  /* Start out with cleared opts. */
118  memset(opts, 0, sizeof(SubOpts));
119 
120  /* caller must expect some option */
121  Assert(supported_opts != 0);
122 
123  /* If connect option is supported, these others also need to be. */
124  Assert(!IsSet(supported_opts, SUBOPT_CONNECT) ||
125  IsSet(supported_opts, SUBOPT_ENABLED | SUBOPT_CREATE_SLOT |
127 
128  /* Set default values for the supported options. */
129  if (IsSet(supported_opts, SUBOPT_CONNECT))
130  opts->connect = true;
131  if (IsSet(supported_opts, SUBOPT_ENABLED))
132  opts->enabled = true;
133  if (IsSet(supported_opts, SUBOPT_CREATE_SLOT))
134  opts->create_slot = true;
135  if (IsSet(supported_opts, SUBOPT_COPY_DATA))
136  opts->copy_data = true;
137  if (IsSet(supported_opts, SUBOPT_REFRESH))
138  opts->refresh = true;
139  if (IsSet(supported_opts, SUBOPT_BINARY))
140  opts->binary = false;
141  if (IsSet(supported_opts, SUBOPT_STREAMING))
142  opts->streaming = LOGICALREP_STREAM_OFF;
143  if (IsSet(supported_opts, SUBOPT_TWOPHASE_COMMIT))
144  opts->twophase = false;
145  if (IsSet(supported_opts, SUBOPT_DISABLE_ON_ERR))
146  opts->disableonerr = false;
147  if (IsSet(supported_opts, SUBOPT_ORIGIN))
149 
150  /* Parse options */
151  foreach(lc, stmt_options)
152  {
153  DefElem *defel = (DefElem *) lfirst(lc);
154 
155  if (IsSet(supported_opts, SUBOPT_CONNECT) &&
156  strcmp(defel->defname, "connect") == 0)
157  {
158  if (IsSet(opts->specified_opts, SUBOPT_CONNECT))
159  errorConflictingDefElem(defel, pstate);
160 
161  opts->specified_opts |= SUBOPT_CONNECT;
162  opts->connect = defGetBoolean(defel);
163  }
164  else if (IsSet(supported_opts, SUBOPT_ENABLED) &&
165  strcmp(defel->defname, "enabled") == 0)
166  {
167  if (IsSet(opts->specified_opts, SUBOPT_ENABLED))
168  errorConflictingDefElem(defel, pstate);
169 
170  opts->specified_opts |= SUBOPT_ENABLED;
171  opts->enabled = defGetBoolean(defel);
172  }
173  else if (IsSet(supported_opts, SUBOPT_CREATE_SLOT) &&
174  strcmp(defel->defname, "create_slot") == 0)
175  {
176  if (IsSet(opts->specified_opts, SUBOPT_CREATE_SLOT))
177  errorConflictingDefElem(defel, pstate);
178 
179  opts->specified_opts |= SUBOPT_CREATE_SLOT;
180  opts->create_slot = defGetBoolean(defel);
181  }
182  else if (IsSet(supported_opts, SUBOPT_SLOT_NAME) &&
183  strcmp(defel->defname, "slot_name") == 0)
184  {
185  if (IsSet(opts->specified_opts, SUBOPT_SLOT_NAME))
186  errorConflictingDefElem(defel, pstate);
187 
188  opts->specified_opts |= SUBOPT_SLOT_NAME;
189  opts->slot_name = defGetString(defel);
190 
191  /* Setting slot_name = NONE is treated as no slot name. */
192  if (strcmp(opts->slot_name, "none") == 0)
193  opts->slot_name = NULL;
194  else
196  }
197  else if (IsSet(supported_opts, SUBOPT_COPY_DATA) &&
198  strcmp(defel->defname, "copy_data") == 0)
199  {
200  if (IsSet(opts->specified_opts, SUBOPT_COPY_DATA))
201  errorConflictingDefElem(defel, pstate);
202 
203  opts->specified_opts |= SUBOPT_COPY_DATA;
204  opts->copy_data = defGetBoolean(defel);
205  }
206  else if (IsSet(supported_opts, SUBOPT_SYNCHRONOUS_COMMIT) &&
207  strcmp(defel->defname, "synchronous_commit") == 0)
208  {
209  if (IsSet(opts->specified_opts, SUBOPT_SYNCHRONOUS_COMMIT))
210  errorConflictingDefElem(defel, pstate);
211 
212  opts->specified_opts |= SUBOPT_SYNCHRONOUS_COMMIT;
213  opts->synchronous_commit = defGetString(defel);
214 
215  /* Test if the given value is valid for synchronous_commit GUC. */
216  (void) set_config_option("synchronous_commit", opts->synchronous_commit,
218  false, 0, false);
219  }
220  else if (IsSet(supported_opts, SUBOPT_REFRESH) &&
221  strcmp(defel->defname, "refresh") == 0)
222  {
223  if (IsSet(opts->specified_opts, SUBOPT_REFRESH))
224  errorConflictingDefElem(defel, pstate);
225 
226  opts->specified_opts |= SUBOPT_REFRESH;
227  opts->refresh = defGetBoolean(defel);
228  }
229  else if (IsSet(supported_opts, SUBOPT_BINARY) &&
230  strcmp(defel->defname, "binary") == 0)
231  {
232  if (IsSet(opts->specified_opts, SUBOPT_BINARY))
233  errorConflictingDefElem(defel, pstate);
234 
235  opts->specified_opts |= SUBOPT_BINARY;
236  opts->binary = defGetBoolean(defel);
237  }
238  else if (IsSet(supported_opts, SUBOPT_STREAMING) &&
239  strcmp(defel->defname, "streaming") == 0)
240  {
241  if (IsSet(opts->specified_opts, SUBOPT_STREAMING))
242  errorConflictingDefElem(defel, pstate);
243 
244  opts->specified_opts |= SUBOPT_STREAMING;
245  opts->streaming = defGetStreamingMode(defel);
246  }
247  else if (strcmp(defel->defname, "two_phase") == 0)
248  {
249  /*
250  * Do not allow toggling of two_phase option. Doing so could cause
251  * missing of transactions and lead to an inconsistent replica.
252  * See comments atop worker.c
253  *
254  * Note: Unsupported twophase indicates that this call originated
255  * from AlterSubscription.
256  */
257  if (!IsSet(supported_opts, SUBOPT_TWOPHASE_COMMIT))
258  ereport(ERROR,
259  (errcode(ERRCODE_SYNTAX_ERROR),
260  errmsg("unrecognized subscription parameter: \"%s\"", defel->defname)));
261 
262  if (IsSet(opts->specified_opts, SUBOPT_TWOPHASE_COMMIT))
263  errorConflictingDefElem(defel, pstate);
264 
265  opts->specified_opts |= SUBOPT_TWOPHASE_COMMIT;
266  opts->twophase = defGetBoolean(defel);
267  }
268  else if (IsSet(supported_opts, SUBOPT_DISABLE_ON_ERR) &&
269  strcmp(defel->defname, "disable_on_error") == 0)
270  {
271  if (IsSet(opts->specified_opts, SUBOPT_DISABLE_ON_ERR))
272  errorConflictingDefElem(defel, pstate);
273 
274  opts->specified_opts |= SUBOPT_DISABLE_ON_ERR;
275  opts->disableonerr = defGetBoolean(defel);
276  }
277  else if (IsSet(supported_opts, SUBOPT_ORIGIN) &&
278  strcmp(defel->defname, "origin") == 0)
279  {
280  if (IsSet(opts->specified_opts, SUBOPT_ORIGIN))
281  errorConflictingDefElem(defel, pstate);
282 
283  opts->specified_opts |= SUBOPT_ORIGIN;
284  pfree(opts->origin);
285 
286  /*
287  * Even though the "origin" parameter allows only "none" and "any"
288  * values, it is implemented as a string type so that the
289  * parameter can be extended in future versions to support
290  * filtering using origin names specified by the user.
291  */
292  opts->origin = defGetString(defel);
293 
294  if ((pg_strcasecmp(opts->origin, LOGICALREP_ORIGIN_NONE) != 0) &&
295  (pg_strcasecmp(opts->origin, LOGICALREP_ORIGIN_ANY) != 0))
296  ereport(ERROR,
297  errcode(ERRCODE_INVALID_PARAMETER_VALUE),
298  errmsg("unrecognized origin value: \"%s\"", opts->origin));
299  }
300  else if (IsSet(supported_opts, SUBOPT_LSN) &&
301  strcmp(defel->defname, "lsn") == 0)
302  {
303  char *lsn_str = defGetString(defel);
304  XLogRecPtr lsn;
305 
306  if (IsSet(opts->specified_opts, SUBOPT_LSN))
307  errorConflictingDefElem(defel, pstate);
308 
309  /* Setting lsn = NONE is treated as resetting LSN */
310  if (strcmp(lsn_str, "none") == 0)
311  lsn = InvalidXLogRecPtr;
312  else
313  {
314  /* Parse the argument as LSN */
316  CStringGetDatum(lsn_str)));
317 
318  if (XLogRecPtrIsInvalid(lsn))
319  ereport(ERROR,
320  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
321  errmsg("invalid WAL location (LSN): %s", lsn_str)));
322  }
323 
324  opts->specified_opts |= SUBOPT_LSN;
325  opts->lsn = lsn;
326  }
327  else
328  ereport(ERROR,
329  (errcode(ERRCODE_SYNTAX_ERROR),
330  errmsg("unrecognized subscription parameter: \"%s\"", defel->defname)));
331  }
332 
333  /*
334  * We've been explicitly asked to not connect, that requires some
335  * additional processing.
336  */
337  if (!opts->connect && IsSet(supported_opts, SUBOPT_CONNECT))
338  {
339  /* Check for incompatible options from the user. */
340  if (opts->enabled &&
341  IsSet(opts->specified_opts, SUBOPT_ENABLED))
342  ereport(ERROR,
343  (errcode(ERRCODE_SYNTAX_ERROR),
344  /*- translator: both %s are strings of the form "option = value" */
345  errmsg("%s and %s are mutually exclusive options",
346  "connect = false", "enabled = true")));
347 
348  if (opts->create_slot &&
349  IsSet(opts->specified_opts, SUBOPT_CREATE_SLOT))
350  ereport(ERROR,
351  (errcode(ERRCODE_SYNTAX_ERROR),
352  errmsg("%s and %s are mutually exclusive options",
353  "connect = false", "create_slot = true")));
354 
355  if (opts->copy_data &&
356  IsSet(opts->specified_opts, SUBOPT_COPY_DATA))
357  ereport(ERROR,
358  (errcode(ERRCODE_SYNTAX_ERROR),
359  errmsg("%s and %s are mutually exclusive options",
360  "connect = false", "copy_data = true")));
361 
362  /* Change the defaults of other options. */
363  opts->enabled = false;
364  opts->create_slot = false;
365  opts->copy_data = false;
366  }
367 
368  /*
369  * Do additional checking for disallowed combination when slot_name = NONE
370  * was used.
371  */
372  if (!opts->slot_name &&
373  IsSet(opts->specified_opts, SUBOPT_SLOT_NAME))
374  {
375  if (opts->enabled)
376  {
377  if (IsSet(opts->specified_opts, SUBOPT_ENABLED))
378  ereport(ERROR,
379  (errcode(ERRCODE_SYNTAX_ERROR),
380  /*- translator: both %s are strings of the form "option = value" */
381  errmsg("%s and %s are mutually exclusive options",
382  "slot_name = NONE", "enabled = true")));
383  else
384  ereport(ERROR,
385  (errcode(ERRCODE_SYNTAX_ERROR),
386  /*- translator: both %s are strings of the form "option = value" */
387  errmsg("subscription with %s must also set %s",
388  "slot_name = NONE", "enabled = false")));
389  }
390 
391  if (opts->create_slot)
392  {
393  if (IsSet(opts->specified_opts, SUBOPT_CREATE_SLOT))
394  ereport(ERROR,
395  (errcode(ERRCODE_SYNTAX_ERROR),
396  /*- translator: both %s are strings of the form "option = value" */
397  errmsg("%s and %s are mutually exclusive options",
398  "slot_name = NONE", "create_slot = true")));
399  else
400  ereport(ERROR,
401  (errcode(ERRCODE_SYNTAX_ERROR),
402  /*- translator: both %s are strings of the form "option = value" */
403  errmsg("subscription with %s must also set %s",
404  "slot_name = NONE", "create_slot = false")));
405  }
406  }
407 }
408 
409 /*
410  * Add publication names from the list to a string.
411  */
412 static void
414 {
415  ListCell *lc;
416  bool first = true;
417 
418  Assert(publications != NIL);
419 
420  foreach(lc, publications)
421  {
422  char *pubname = strVal(lfirst(lc));
423 
424  if (first)
425  first = false;
426  else
428 
429  if (quote_literal)
431  else
432  {
434  appendStringInfoString(dest, pubname);
436  }
437  }
438 }
439 
440 /*
441  * Check that the specified publications are present on the publisher.
442  */
443 static void
445 {
447  StringInfo cmd;
448  TupleTableSlot *slot;
449  List *publicationsCopy = NIL;
450  Oid tableRow[1] = {TEXTOID};
451 
452  cmd = makeStringInfo();
453  appendStringInfoString(cmd, "SELECT t.pubname FROM\n"
454  " pg_catalog.pg_publication t WHERE\n"
455  " t.pubname IN (");
456  get_publications_str(publications, cmd, true);
457  appendStringInfoChar(cmd, ')');
458 
459  res = walrcv_exec(wrconn, cmd->data, 1, tableRow);
460  pfree(cmd->data);
461  pfree(cmd);
462 
463  if (res->status != WALRCV_OK_TUPLES)
464  ereport(ERROR,
465  errmsg("could not receive list of publications from the publisher: %s",
466  res->err));
467 
468  publicationsCopy = list_copy(publications);
469 
470  /* Process publication(s). */
471  slot = MakeSingleTupleTableSlot(res->tupledesc, &TTSOpsMinimalTuple);
472  while (tuplestore_gettupleslot(res->tuplestore, true, false, slot))
473  {
474  char *pubname;
475  bool isnull;
476 
477  pubname = TextDatumGetCString(slot_getattr(slot, 1, &isnull));
478  Assert(!isnull);
479 
480  /* Delete the publication present in publisher from the list. */
481  publicationsCopy = list_delete(publicationsCopy, makeString(pubname));
482  ExecClearTuple(slot);
483  }
484 
486 
488 
489  if (list_length(publicationsCopy))
490  {
491  /* Prepare the list of non-existent publication(s) for error message. */
492  StringInfo pubnames = makeStringInfo();
493 
494  get_publications_str(publicationsCopy, pubnames, false);
496  errcode(ERRCODE_UNDEFINED_OBJECT),
497  errmsg_plural("publication %s does not exist on the publisher",
498  "publications %s do not exist on the publisher",
499  list_length(publicationsCopy),
500  pubnames->data));
501  }
502 }
503 
504 /*
505  * Auxiliary function to build a text array out of a list of String nodes.
506  */
507 static Datum
509 {
510  ArrayType *arr;
511  Datum *datums;
512  MemoryContext memcxt;
513  MemoryContext oldcxt;
514 
515  /* Create memory context for temporary allocations. */
517  "publicationListToArray to array",
519  oldcxt = MemoryContextSwitchTo(memcxt);
520 
521  datums = (Datum *) palloc(sizeof(Datum) * list_length(publist));
522 
523  check_duplicates_in_publist(publist, datums);
524 
525  MemoryContextSwitchTo(oldcxt);
526 
527  arr = construct_array_builtin(datums, list_length(publist), TEXTOID);
528 
529  MemoryContextDelete(memcxt);
530 
531  return PointerGetDatum(arr);
532 }
533 
534 /*
535  * Create new subscription.
536  */
539  bool isTopLevel)
540 {
541  Relation rel;
542  ObjectAddress myself;
543  Oid subid;
544  bool nulls[Natts_pg_subscription];
545  Datum values[Natts_pg_subscription];
546  Oid owner = GetUserId();
547  HeapTuple tup;
548  char *conninfo;
549  char originname[NAMEDATALEN];
550  List *publications;
551  bits32 supported_opts;
552  SubOpts opts = {0};
553 
554  /*
555  * Parse and check options.
556  *
557  * Connection and publication should not be specified here.
558  */
559  supported_opts = (SUBOPT_CONNECT | SUBOPT_ENABLED | SUBOPT_CREATE_SLOT |
564  parse_subscription_options(pstate, stmt->options, supported_opts, &opts);
565 
566  /*
567  * Since creating a replication slot is not transactional, rolling back
568  * the transaction leaves the created replication slot. So we cannot run
569  * CREATE SUBSCRIPTION inside a transaction block if creating a
570  * replication slot.
571  */
572  if (opts.create_slot)
573  PreventInTransactionBlock(isTopLevel, "CREATE SUBSCRIPTION ... WITH (create_slot = true)");
574 
575  if (!superuser())
576  ereport(ERROR,
577  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
578  errmsg("must be superuser to create subscriptions")));
579 
580  /*
581  * If built with appropriate switch, whine when regression-testing
582  * conventions for subscription names are violated.
583  */
584 #ifdef ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS
585  if (strncmp(stmt->subname, "regress_", 8) != 0)
586  elog(WARNING, "subscriptions created by regression test cases should have names starting with \"regress_\"");
587 #endif
588 
589  rel = table_open(SubscriptionRelationId, RowExclusiveLock);
590 
591  /* Check if name is used */
592  subid = GetSysCacheOid2(SUBSCRIPTIONNAME, Anum_pg_subscription_oid,
593  MyDatabaseId, CStringGetDatum(stmt->subname));
594  if (OidIsValid(subid))
595  {
596  ereport(ERROR,
598  errmsg("subscription \"%s\" already exists",
599  stmt->subname)));
600  }
601 
602  if (!IsSet(opts.specified_opts, SUBOPT_SLOT_NAME) &&
603  opts.slot_name == NULL)
604  opts.slot_name = stmt->subname;
605 
606  /* The default for synchronous_commit of subscriptions is off. */
607  if (opts.synchronous_commit == NULL)
608  opts.synchronous_commit = "off";
609 
610  conninfo = stmt->conninfo;
611  publications = stmt->publication;
612 
613  /* Load the library providing us libpq calls. */
614  load_file("libpqwalreceiver", false);
615 
616  /* Check the connection info string. */
617  walrcv_check_conninfo(conninfo);
618 
619  /* Everything ok, form a new tuple. */
620  memset(values, 0, sizeof(values));
621  memset(nulls, false, sizeof(nulls));
622 
623  subid = GetNewOidWithIndex(rel, SubscriptionObjectIndexId,
624  Anum_pg_subscription_oid);
625  values[Anum_pg_subscription_oid - 1] = ObjectIdGetDatum(subid);
626  values[Anum_pg_subscription_subdbid - 1] = ObjectIdGetDatum(MyDatabaseId);
627  values[Anum_pg_subscription_subskiplsn - 1] = LSNGetDatum(InvalidXLogRecPtr);
628  values[Anum_pg_subscription_subname - 1] =
630  values[Anum_pg_subscription_subowner - 1] = ObjectIdGetDatum(owner);
631  values[Anum_pg_subscription_subenabled - 1] = BoolGetDatum(opts.enabled);
632  values[Anum_pg_subscription_subbinary - 1] = BoolGetDatum(opts.binary);
633  values[Anum_pg_subscription_substream - 1] = CharGetDatum(opts.streaming);
634  values[Anum_pg_subscription_subtwophasestate - 1] =
635  CharGetDatum(opts.twophase ?
638  values[Anum_pg_subscription_subdisableonerr - 1] = BoolGetDatum(opts.disableonerr);
639  values[Anum_pg_subscription_subconninfo - 1] =
640  CStringGetTextDatum(conninfo);
641  if (opts.slot_name)
642  values[Anum_pg_subscription_subslotname - 1] =
644  else
645  nulls[Anum_pg_subscription_subslotname - 1] = true;
646  values[Anum_pg_subscription_subsynccommit - 1] =
647  CStringGetTextDatum(opts.synchronous_commit);
648  values[Anum_pg_subscription_subpublications - 1] =
649  publicationListToArray(publications);
650  values[Anum_pg_subscription_suborigin - 1] =
651  CStringGetTextDatum(opts.origin);
652 
653  tup = heap_form_tuple(RelationGetDescr(rel), values, nulls);
654 
655  /* Insert tuple into catalog. */
656  CatalogTupleInsert(rel, tup);
657  heap_freetuple(tup);
658 
659  recordDependencyOnOwner(SubscriptionRelationId, subid, owner);
660 
661  ReplicationOriginNameForLogicalRep(subid, InvalidOid, originname, sizeof(originname));
662  replorigin_create(originname);
663 
664  /*
665  * Connect to remote side to execute requested commands and fetch table
666  * info.
667  */
668  if (opts.connect)
669  {
670  char *err;
672  List *tables;
673  ListCell *lc;
674  char table_state;
675 
676  /* Try to connect to the publisher. */
677  wrconn = walrcv_connect(conninfo, true, stmt->subname, &err);
678  if (!wrconn)
679  ereport(ERROR,
680  (errcode(ERRCODE_CONNECTION_FAILURE),
681  errmsg("could not connect to the publisher: %s", err)));
682 
683  PG_TRY();
684  {
685  check_publications(wrconn, publications);
686  check_publications_origin(wrconn, publications, opts.copy_data,
687  opts.origin, NULL, 0, stmt->subname);
688 
689  /*
690  * Set sync state based on if we were asked to do data copy or
691  * not.
692  */
693  table_state = opts.copy_data ? SUBREL_STATE_INIT : SUBREL_STATE_READY;
694 
695  /*
696  * Get the table list from publisher and build local table status
697  * info.
698  */
699  tables = fetch_table_list(wrconn, publications);
700  foreach(lc, tables)
701  {
702  RangeVar *rv = (RangeVar *) lfirst(lc);
703  Oid relid;
704 
705  relid = RangeVarGetRelid(rv, AccessShareLock, false);
706 
707  /* Check for supported relkind. */
709  rv->schemaname, rv->relname);
710 
711  AddSubscriptionRelState(subid, relid, table_state,
713  }
714 
715  /*
716  * If requested, create permanent slot for the subscription. We
717  * won't use the initial snapshot for anything, so no need to
718  * export it.
719  */
720  if (opts.create_slot)
721  {
722  bool twophase_enabled = false;
723 
724  Assert(opts.slot_name);
725 
726  /*
727  * Even if two_phase is set, don't create the slot with
728  * two-phase enabled. Will enable it once all the tables are
729  * synced and ready. This avoids race-conditions like prepared
730  * transactions being skipped due to changes not being applied
731  * due to checks in should_apply_changes_for_rel() when
732  * tablesync for the corresponding tables are in progress. See
733  * comments atop worker.c.
734  *
735  * Note that if tables were specified but copy_data is false
736  * then it is safe to enable two_phase up-front because those
737  * tables are already initially in READY state. When the
738  * subscription has no tables, we leave the twophase state as
739  * PENDING, to allow ALTER SUBSCRIPTION ... REFRESH
740  * PUBLICATION to work.
741  */
742  if (opts.twophase && !opts.copy_data && tables != NIL)
743  twophase_enabled = true;
744 
745  walrcv_create_slot(wrconn, opts.slot_name, false, twophase_enabled,
746  CRS_NOEXPORT_SNAPSHOT, NULL);
747 
748  if (twophase_enabled)
750 
751  ereport(NOTICE,
752  (errmsg("created replication slot \"%s\" on publisher",
753  opts.slot_name)));
754  }
755  }
756  PG_FINALLY();
757  {
759  }
760  PG_END_TRY();
761  }
762  else
764  (errmsg("subscription was created, but is not connected"),
765  errhint("To initiate replication, you must manually create the replication slot, enable the subscription, and refresh the subscription.")));
766 
768 
770 
771  if (opts.enabled)
773 
774  ObjectAddressSet(myself, SubscriptionRelationId, subid);
775 
776  InvokeObjectPostCreateHook(SubscriptionRelationId, subid, 0);
777 
778  return myself;
779 }
780 
781 static void
783  List *validate_publications)
784 {
785  char *err;
786  List *pubrel_names;
787  List *subrel_states;
788  Oid *subrel_local_oids;
789  Oid *pubrel_local_oids;
790  ListCell *lc;
791  int off;
792  int remove_rel_len;
793  int subrel_count;
794  Relation rel = NULL;
795  typedef struct SubRemoveRels
796  {
797  Oid relid;
798  char state;
799  } SubRemoveRels;
800  SubRemoveRels *sub_remove_rels;
802 
803  /* Load the library providing us libpq calls. */
804  load_file("libpqwalreceiver", false);
805 
806  /* Try to connect to the publisher. */
807  wrconn = walrcv_connect(sub->conninfo, true, sub->name, &err);
808  if (!wrconn)
809  ereport(ERROR,
810  (errcode(ERRCODE_CONNECTION_FAILURE),
811  errmsg("could not connect to the publisher: %s", err)));
812 
813  PG_TRY();
814  {
815  if (validate_publications)
816  check_publications(wrconn, validate_publications);
817 
818  /* Get the table list from publisher. */
819  pubrel_names = fetch_table_list(wrconn, sub->publications);
820 
821  /* Get local table list. */
822  subrel_states = GetSubscriptionRelations(sub->oid, false);
823  subrel_count = list_length(subrel_states);
824 
825  /*
826  * Build qsorted array of local table oids for faster lookup. This can
827  * potentially contain all tables in the database so speed of lookup
828  * is important.
829  */
830  subrel_local_oids = palloc(subrel_count * sizeof(Oid));
831  off = 0;
832  foreach(lc, subrel_states)
833  {
835 
836  subrel_local_oids[off++] = relstate->relid;
837  }
838  qsort(subrel_local_oids, subrel_count,
839  sizeof(Oid), oid_cmp);
840 
842  sub->origin, subrel_local_oids,
843  subrel_count, sub->name);
844 
845  /*
846  * Rels that we want to remove from subscription and drop any slots
847  * and origins corresponding to them.
848  */
849  sub_remove_rels = palloc(subrel_count * sizeof(SubRemoveRels));
850 
851  /*
852  * Walk over the remote tables and try to match them to locally known
853  * tables. If the table is not known locally create a new state for
854  * it.
855  *
856  * Also builds array of local oids of remote tables for the next step.
857  */
858  off = 0;
859  pubrel_local_oids = palloc(list_length(pubrel_names) * sizeof(Oid));
860 
861  foreach(lc, pubrel_names)
862  {
863  RangeVar *rv = (RangeVar *) lfirst(lc);
864  Oid relid;
865 
866  relid = RangeVarGetRelid(rv, AccessShareLock, false);
867 
868  /* Check for supported relkind. */
870  rv->schemaname, rv->relname);
871 
872  pubrel_local_oids[off++] = relid;
873 
874  if (!bsearch(&relid, subrel_local_oids,
875  subrel_count, sizeof(Oid), oid_cmp))
876  {
877  AddSubscriptionRelState(sub->oid, relid,
878  copy_data ? SUBREL_STATE_INIT : SUBREL_STATE_READY,
880  ereport(DEBUG1,
881  (errmsg_internal("table \"%s.%s\" added to subscription \"%s\"",
882  rv->schemaname, rv->relname, sub->name)));
883  }
884  }
885 
886  /*
887  * Next remove state for tables we should not care about anymore using
888  * the data we collected above
889  */
890  qsort(pubrel_local_oids, list_length(pubrel_names),
891  sizeof(Oid), oid_cmp);
892 
893  remove_rel_len = 0;
894  for (off = 0; off < subrel_count; off++)
895  {
896  Oid relid = subrel_local_oids[off];
897 
898  if (!bsearch(&relid, pubrel_local_oids,
899  list_length(pubrel_names), sizeof(Oid), oid_cmp))
900  {
901  char state;
902  XLogRecPtr statelsn;
903 
904  /*
905  * Lock pg_subscription_rel with AccessExclusiveLock to
906  * prevent any race conditions with the apply worker
907  * re-launching workers at the same time this code is trying
908  * to remove those tables.
909  *
910  * Even if new worker for this particular rel is restarted it
911  * won't be able to make any progress as we hold exclusive
912  * lock on subscription_rel till the transaction end. It will
913  * simply exit as there is no corresponding rel entry.
914  *
915  * This locking also ensures that the state of rels won't
916  * change till we are done with this refresh operation.
917  */
918  if (!rel)
919  rel = table_open(SubscriptionRelRelationId, AccessExclusiveLock);
920 
921  /* Last known rel state. */
922  state = GetSubscriptionRelState(sub->oid, relid, &statelsn);
923 
924  sub_remove_rels[remove_rel_len].relid = relid;
925  sub_remove_rels[remove_rel_len++].state = state;
926 
927  RemoveSubscriptionRel(sub->oid, relid);
928 
929  logicalrep_worker_stop(sub->oid, relid);
930 
931  /*
932  * For READY state, we would have already dropped the
933  * tablesync origin.
934  */
935  if (state != SUBREL_STATE_READY)
936  {
937  char originname[NAMEDATALEN];
938 
939  /*
940  * Drop the tablesync's origin tracking if exists.
941  *
942  * It is possible that the origin is not yet created for
943  * tablesync worker, this can happen for the states before
944  * SUBREL_STATE_FINISHEDCOPY. The tablesync worker or
945  * apply worker can also concurrently try to drop the
946  * origin and by this time the origin might be already
947  * removed. For these reasons, passing missing_ok = true.
948  */
949  ReplicationOriginNameForLogicalRep(sub->oid, relid, originname,
950  sizeof(originname));
951  replorigin_drop_by_name(originname, true, false);
952  }
953 
954  ereport(DEBUG1,
955  (errmsg_internal("table \"%s.%s\" removed from subscription \"%s\"",
957  get_rel_name(relid),
958  sub->name)));
959  }
960  }
961 
962  /*
963  * Drop the tablesync slots associated with removed tables. This has
964  * to be at the end because otherwise if there is an error while doing
965  * the database operations we won't be able to rollback dropped slots.
966  */
967  for (off = 0; off < remove_rel_len; off++)
968  {
969  if (sub_remove_rels[off].state != SUBREL_STATE_READY &&
970  sub_remove_rels[off].state != SUBREL_STATE_SYNCDONE)
971  {
972  char syncslotname[NAMEDATALEN] = {0};
973 
974  /*
975  * For READY/SYNCDONE states we know the tablesync slot has
976  * already been dropped by the tablesync worker.
977  *
978  * For other states, there is no certainty, maybe the slot
979  * does not exist yet. Also, if we fail after removing some of
980  * the slots, next time, it will again try to drop already
981  * dropped slots and fail. For these reasons, we allow
982  * missing_ok = true for the drop.
983  */
984  ReplicationSlotNameForTablesync(sub->oid, sub_remove_rels[off].relid,
985  syncslotname, sizeof(syncslotname));
986  ReplicationSlotDropAtPubNode(wrconn, syncslotname, true);
987  }
988  }
989  }
990  PG_FINALLY();
991  {
993  }
994  PG_END_TRY();
995 
996  if (rel)
997  table_close(rel, NoLock);
998 }
999 
1000 /*
1001  * Alter the existing subscription.
1002  */
1005  bool isTopLevel)
1006 {
1007  Relation rel;
1008  ObjectAddress myself;
1009  bool nulls[Natts_pg_subscription];
1010  bool replaces[Natts_pg_subscription];
1011  Datum values[Natts_pg_subscription];
1012  HeapTuple tup;
1013  Oid subid;
1014  bool update_tuple = false;
1015  Subscription *sub;
1016  Form_pg_subscription form;
1017  bits32 supported_opts;
1018  SubOpts opts = {0};
1019 
1020  rel = table_open(SubscriptionRelationId, RowExclusiveLock);
1021 
1022  /* Fetch the existing tuple. */
1024  CStringGetDatum(stmt->subname));
1025 
1026  if (!HeapTupleIsValid(tup))
1027  ereport(ERROR,
1028  (errcode(ERRCODE_UNDEFINED_OBJECT),
1029  errmsg("subscription \"%s\" does not exist",
1030  stmt->subname)));
1031 
1032  form = (Form_pg_subscription) GETSTRUCT(tup);
1033  subid = form->oid;
1034 
1035  /* must be owner */
1036  if (!object_ownercheck(SubscriptionRelationId, subid, GetUserId()))
1038  stmt->subname);
1039 
1040  sub = GetSubscription(subid, false);
1041 
1042  /* Lock the subscription so nobody else can do anything with it. */
1043  LockSharedObject(SubscriptionRelationId, subid, 0, AccessExclusiveLock);
1044 
1045  /* Form a new tuple. */
1046  memset(values, 0, sizeof(values));
1047  memset(nulls, false, sizeof(nulls));
1048  memset(replaces, false, sizeof(replaces));
1049 
1050  switch (stmt->kind)
1051  {
1053  {
1054  supported_opts = (SUBOPT_SLOT_NAME |
1057  SUBOPT_ORIGIN);
1058 
1059  parse_subscription_options(pstate, stmt->options,
1060  supported_opts, &opts);
1061 
1062  if (IsSet(opts.specified_opts, SUBOPT_SLOT_NAME))
1063  {
1064  /*
1065  * The subscription must be disabled to allow slot_name as
1066  * 'none', otherwise, the apply worker will repeatedly try
1067  * to stream the data using that slot_name which neither
1068  * exists on the publisher nor the user will be allowed to
1069  * create it.
1070  */
1071  if (sub->enabled && !opts.slot_name)
1072  ereport(ERROR,
1073  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1074  errmsg("cannot set %s for enabled subscription",
1075  "slot_name = NONE")));
1076 
1077  if (opts.slot_name)
1078  values[Anum_pg_subscription_subslotname - 1] =
1080  else
1081  nulls[Anum_pg_subscription_subslotname - 1] = true;
1082  replaces[Anum_pg_subscription_subslotname - 1] = true;
1083  }
1084 
1085  if (opts.synchronous_commit)
1086  {
1087  values[Anum_pg_subscription_subsynccommit - 1] =
1088  CStringGetTextDatum(opts.synchronous_commit);
1089  replaces[Anum_pg_subscription_subsynccommit - 1] = true;
1090  }
1091 
1092  if (IsSet(opts.specified_opts, SUBOPT_BINARY))
1093  {
1094  values[Anum_pg_subscription_subbinary - 1] =
1095  BoolGetDatum(opts.binary);
1096  replaces[Anum_pg_subscription_subbinary - 1] = true;
1097  }
1098 
1099  if (IsSet(opts.specified_opts, SUBOPT_STREAMING))
1100  {
1101  values[Anum_pg_subscription_substream - 1] =
1102  CharGetDatum(opts.streaming);
1103  replaces[Anum_pg_subscription_substream - 1] = true;
1104  }
1105 
1106  if (IsSet(opts.specified_opts, SUBOPT_DISABLE_ON_ERR))
1107  {
1108  values[Anum_pg_subscription_subdisableonerr - 1]
1109  = BoolGetDatum(opts.disableonerr);
1110  replaces[Anum_pg_subscription_subdisableonerr - 1]
1111  = true;
1112  }
1113 
1114  if (IsSet(opts.specified_opts, SUBOPT_ORIGIN))
1115  {
1116  values[Anum_pg_subscription_suborigin - 1] =
1117  CStringGetTextDatum(opts.origin);
1118  replaces[Anum_pg_subscription_suborigin - 1] = true;
1119  }
1120 
1121  update_tuple = true;
1122  break;
1123  }
1124 
1126  {
1127  parse_subscription_options(pstate, stmt->options,
1128  SUBOPT_ENABLED, &opts);
1129  Assert(IsSet(opts.specified_opts, SUBOPT_ENABLED));
1130 
1131  if (!sub->slotname && opts.enabled)
1132  ereport(ERROR,
1133  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1134  errmsg("cannot enable subscription that does not have a slot name")));
1135 
1136  values[Anum_pg_subscription_subenabled - 1] =
1137  BoolGetDatum(opts.enabled);
1138  replaces[Anum_pg_subscription_subenabled - 1] = true;
1139 
1140  if (opts.enabled)
1142 
1143  update_tuple = true;
1144  break;
1145  }
1146 
1148  /* Load the library providing us libpq calls. */
1149  load_file("libpqwalreceiver", false);
1150  /* Check the connection info string. */
1151  walrcv_check_conninfo(stmt->conninfo);
1152 
1153  values[Anum_pg_subscription_subconninfo - 1] =
1154  CStringGetTextDatum(stmt->conninfo);
1155  replaces[Anum_pg_subscription_subconninfo - 1] = true;
1156  update_tuple = true;
1157  break;
1158 
1160  {
1161  supported_opts = SUBOPT_COPY_DATA | SUBOPT_REFRESH;
1162  parse_subscription_options(pstate, stmt->options,
1163  supported_opts, &opts);
1164 
1165  values[Anum_pg_subscription_subpublications - 1] =
1166  publicationListToArray(stmt->publication);
1167  replaces[Anum_pg_subscription_subpublications - 1] = true;
1168 
1169  update_tuple = true;
1170 
1171  /* Refresh if user asked us to. */
1172  if (opts.refresh)
1173  {
1174  if (!sub->enabled)
1175  ereport(ERROR,
1176  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1177  errmsg("ALTER SUBSCRIPTION with refresh is not allowed for disabled subscriptions"),
1178  errhint("Use ALTER SUBSCRIPTION ... SET PUBLICATION ... WITH (refresh = false).")));
1179 
1180  /*
1181  * See ALTER_SUBSCRIPTION_REFRESH for details why this is
1182  * not allowed.
1183  */
1184  if (sub->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED && opts.copy_data)
1185  ereport(ERROR,
1186  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1187  errmsg("ALTER SUBSCRIPTION with refresh and copy_data is not allowed when two_phase is enabled"),
1188  errhint("Use ALTER SUBSCRIPTION ... SET PUBLICATION with refresh = false, or with copy_data = false, or use DROP/CREATE SUBSCRIPTION.")));
1189 
1190  PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION with refresh");
1191 
1192  /* Make sure refresh sees the new list of publications. */
1193  sub->publications = stmt->publication;
1194 
1195  AlterSubscription_refresh(sub, opts.copy_data,
1196  stmt->publication);
1197  }
1198 
1199  break;
1200  }
1201 
1204  {
1205  List *publist;
1206  bool isadd = stmt->kind == ALTER_SUBSCRIPTION_ADD_PUBLICATION;
1207 
1208  supported_opts = SUBOPT_REFRESH | SUBOPT_COPY_DATA;
1209  parse_subscription_options(pstate, stmt->options,
1210  supported_opts, &opts);
1211 
1212  publist = merge_publications(sub->publications, stmt->publication, isadd, stmt->subname);
1213  values[Anum_pg_subscription_subpublications - 1] =
1214  publicationListToArray(publist);
1215  replaces[Anum_pg_subscription_subpublications - 1] = true;
1216 
1217  update_tuple = true;
1218 
1219  /* Refresh if user asked us to. */
1220  if (opts.refresh)
1221  {
1222  /* We only need to validate user specified publications. */
1223  List *validate_publications = (isadd) ? stmt->publication : NULL;
1224 
1225  if (!sub->enabled)
1226  ereport(ERROR,
1227  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1228  errmsg("ALTER SUBSCRIPTION with refresh is not allowed for disabled subscriptions"),
1229  /* translator: %s is an SQL ALTER command */
1230  errhint("Use %s instead.",
1231  isadd ?
1232  "ALTER SUBSCRIPTION ... ADD PUBLICATION ... WITH (refresh = false)" :
1233  "ALTER SUBSCRIPTION ... DROP PUBLICATION ... WITH (refresh = false)")));
1234 
1235  /*
1236  * See ALTER_SUBSCRIPTION_REFRESH for details why this is
1237  * not allowed.
1238  */
1239  if (sub->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED && opts.copy_data)
1240  ereport(ERROR,
1241  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1242  errmsg("ALTER SUBSCRIPTION with refresh and copy_data is not allowed when two_phase is enabled"),
1243  /* translator: %s is an SQL ALTER command */
1244  errhint("Use %s with refresh = false, or with copy_data = false, or use DROP/CREATE SUBSCRIPTION.",
1245  isadd ?
1246  "ALTER SUBSCRIPTION ... ADD PUBLICATION" :
1247  "ALTER SUBSCRIPTION ... DROP PUBLICATION")));
1248 
1249  PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION with refresh");
1250 
1251  /* Refresh the new list of publications. */
1252  sub->publications = publist;
1253 
1254  AlterSubscription_refresh(sub, opts.copy_data,
1255  validate_publications);
1256  }
1257 
1258  break;
1259  }
1260 
1262  {
1263  if (!sub->enabled)
1264  ereport(ERROR,
1265  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1266  errmsg("ALTER SUBSCRIPTION ... REFRESH is not allowed for disabled subscriptions")));
1267 
1268  parse_subscription_options(pstate, stmt->options,
1270 
1271  /*
1272  * The subscription option "two_phase" requires that
1273  * replication has passed the initial table synchronization
1274  * phase before the two_phase becomes properly enabled.
1275  *
1276  * But, having reached this two-phase commit "enabled" state
1277  * we must not allow any subsequent table initialization to
1278  * occur. So the ALTER SUBSCRIPTION ... REFRESH is disallowed
1279  * when the user had requested two_phase = on mode.
1280  *
1281  * The exception to this restriction is when copy_data =
1282  * false, because when copy_data is false the tablesync will
1283  * start already in READY state and will exit directly without
1284  * doing anything.
1285  *
1286  * For more details see comments atop worker.c.
1287  */
1288  if (sub->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED && opts.copy_data)
1289  ereport(ERROR,
1290  (errcode(ERRCODE_SYNTAX_ERROR),
1291  errmsg("ALTER SUBSCRIPTION ... REFRESH with copy_data is not allowed when two_phase is enabled"),
1292  errhint("Use ALTER SUBSCRIPTION ... REFRESH with copy_data = false, or use DROP/CREATE SUBSCRIPTION.")));
1293 
1294  PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION ... REFRESH");
1295 
1296  AlterSubscription_refresh(sub, opts.copy_data, NULL);
1297 
1298  break;
1299  }
1300 
1302  {
1303  parse_subscription_options(pstate, stmt->options, SUBOPT_LSN, &opts);
1304 
1305  /* ALTER SUBSCRIPTION ... SKIP supports only LSN option */
1306  Assert(IsSet(opts.specified_opts, SUBOPT_LSN));
1307 
1308  if (!superuser())
1309  ereport(ERROR,
1310  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1311  errmsg("must be superuser to skip transaction")));
1312 
1313  /*
1314  * If the user sets subskiplsn, we do a sanity check to make
1315  * sure that the specified LSN is a probable value.
1316  */
1317  if (!XLogRecPtrIsInvalid(opts.lsn))
1318  {
1319  RepOriginId originid;
1320  char originname[NAMEDATALEN];
1321  XLogRecPtr remote_lsn;
1322 
1324  originname, sizeof(originname));
1325  originid = replorigin_by_name(originname, false);
1326  remote_lsn = replorigin_get_progress(originid, false);
1327 
1328  /* Check the given LSN is at least a future LSN */
1329  if (!XLogRecPtrIsInvalid(remote_lsn) && opts.lsn < remote_lsn)
1330  ereport(ERROR,
1331  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1332  errmsg("skip WAL location (LSN %X/%X) must be greater than origin LSN %X/%X",
1333  LSN_FORMAT_ARGS(opts.lsn),
1334  LSN_FORMAT_ARGS(remote_lsn))));
1335  }
1336 
1337  values[Anum_pg_subscription_subskiplsn - 1] = LSNGetDatum(opts.lsn);
1338  replaces[Anum_pg_subscription_subskiplsn - 1] = true;
1339 
1340  update_tuple = true;
1341  break;
1342  }
1343 
1344  default:
1345  elog(ERROR, "unrecognized ALTER SUBSCRIPTION kind %d",
1346  stmt->kind);
1347  }
1348 
1349  /* Update the catalog if needed. */
1350  if (update_tuple)
1351  {
1352  tup = heap_modify_tuple(tup, RelationGetDescr(rel), values, nulls,
1353  replaces);
1354 
1355  CatalogTupleUpdate(rel, &tup->t_self, tup);
1356 
1357  heap_freetuple(tup);
1358  }
1359 
1361 
1362  ObjectAddressSet(myself, SubscriptionRelationId, subid);
1363 
1364  InvokeObjectPostAlterHook(SubscriptionRelationId, subid, 0);
1365 
1366  /* Wake up related replication workers to handle this change quickly. */
1368 
1369  return myself;
1370 }
1371 
1372 /*
1373  * Drop a subscription
1374  */
1375 void
1377 {
1378  Relation rel;
1379  ObjectAddress myself;
1380  HeapTuple tup;
1381  Oid subid;
1382  Datum datum;
1383  bool isnull;
1384  char *subname;
1385  char *conninfo;
1386  char *slotname;
1387  List *subworkers;
1388  ListCell *lc;
1389  char originname[NAMEDATALEN];
1390  char *err = NULL;
1392  Form_pg_subscription form;
1393  List *rstates;
1394 
1395  /*
1396  * Lock pg_subscription with AccessExclusiveLock to ensure that the
1397  * launcher doesn't restart new worker during dropping the subscription
1398  */
1399  rel = table_open(SubscriptionRelationId, AccessExclusiveLock);
1400 
1402  CStringGetDatum(stmt->subname));
1403 
1404  if (!HeapTupleIsValid(tup))
1405  {
1406  table_close(rel, NoLock);
1407 
1408  if (!stmt->missing_ok)
1409  ereport(ERROR,
1410  (errcode(ERRCODE_UNDEFINED_OBJECT),
1411  errmsg("subscription \"%s\" does not exist",
1412  stmt->subname)));
1413  else
1414  ereport(NOTICE,
1415  (errmsg("subscription \"%s\" does not exist, skipping",
1416  stmt->subname)));
1417 
1418  return;
1419  }
1420 
1421  form = (Form_pg_subscription) GETSTRUCT(tup);
1422  subid = form->oid;
1423 
1424  /* must be owner */
1425  if (!object_ownercheck(SubscriptionRelationId, subid, GetUserId()))
1427  stmt->subname);
1428 
1429  /* DROP hook for the subscription being removed */
1430  InvokeObjectDropHook(SubscriptionRelationId, subid, 0);
1431 
1432  /*
1433  * Lock the subscription so nobody else can do anything with it (including
1434  * the replication workers).
1435  */
1436  LockSharedObject(SubscriptionRelationId, subid, 0, AccessExclusiveLock);
1437 
1438  /* Get subname */
1439  datum = SysCacheGetAttr(SUBSCRIPTIONOID, tup,
1440  Anum_pg_subscription_subname, &isnull);
1441  Assert(!isnull);
1442  subname = pstrdup(NameStr(*DatumGetName(datum)));
1443 
1444  /* Get conninfo */
1445  datum = SysCacheGetAttr(SUBSCRIPTIONOID, tup,
1446  Anum_pg_subscription_subconninfo, &isnull);
1447  Assert(!isnull);
1448  conninfo = TextDatumGetCString(datum);
1449 
1450  /* Get slotname */
1451  datum = SysCacheGetAttr(SUBSCRIPTIONOID, tup,
1452  Anum_pg_subscription_subslotname, &isnull);
1453  if (!isnull)
1454  slotname = pstrdup(NameStr(*DatumGetName(datum)));
1455  else
1456  slotname = NULL;
1457 
1458  /*
1459  * Since dropping a replication slot is not transactional, the replication
1460  * slot stays dropped even if the transaction rolls back. So we cannot
1461  * run DROP SUBSCRIPTION inside a transaction block if dropping the
1462  * replication slot. Also, in this case, we report a message for dropping
1463  * the subscription to the cumulative stats system.
1464  *
1465  * XXX The command name should really be something like "DROP SUBSCRIPTION
1466  * of a subscription that is associated with a replication slot", but we
1467  * don't have the proper facilities for that.
1468  */
1469  if (slotname)
1470  PreventInTransactionBlock(isTopLevel, "DROP SUBSCRIPTION");
1471 
1472  ObjectAddressSet(myself, SubscriptionRelationId, subid);
1473  EventTriggerSQLDropAddObject(&myself, true, true);
1474 
1475  /* Remove the tuple from catalog. */
1476  CatalogTupleDelete(rel, &tup->t_self);
1477 
1478  ReleaseSysCache(tup);
1479 
1480  /*
1481  * Stop all the subscription workers immediately.
1482  *
1483  * This is necessary if we are dropping the replication slot, so that the
1484  * slot becomes accessible.
1485  *
1486  * It is also necessary if the subscription is disabled and was disabled
1487  * in the same transaction. Then the workers haven't seen the disabling
1488  * yet and will still be running, leading to hangs later when we want to
1489  * drop the replication origin. If the subscription was disabled before
1490  * this transaction, then there shouldn't be any workers left, so this
1491  * won't make a difference.
1492  *
1493  * New workers won't be started because we hold an exclusive lock on the
1494  * subscription till the end of the transaction.
1495  */
1496  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
1497  subworkers = logicalrep_workers_find(subid, false);
1498  LWLockRelease(LogicalRepWorkerLock);
1499  foreach(lc, subworkers)
1500  {
1502 
1504  }
1505  list_free(subworkers);
1506 
1507  /*
1508  * Remove the no-longer-useful entry in the launcher's table of apply
1509  * worker start times.
1510  *
1511  * If this transaction rolls back, the launcher might restart a failed
1512  * apply worker before wal_retrieve_retry_interval milliseconds have
1513  * elapsed, but that's pretty harmless.
1514  */
1516 
1517  /*
1518  * Cleanup of tablesync replication origins.
1519  *
1520  * Any READY-state relations would already have dealt with clean-ups.
1521  *
1522  * Note that the state can't change because we have already stopped both
1523  * the apply and tablesync workers and they can't restart because of
1524  * exclusive lock on the subscription.
1525  */
1526  rstates = GetSubscriptionRelations(subid, true);
1527  foreach(lc, rstates)
1528  {
1530  Oid relid = rstate->relid;
1531 
1532  /* Only cleanup resources of tablesync workers */
1533  if (!OidIsValid(relid))
1534  continue;
1535 
1536  /*
1537  * Drop the tablesync's origin tracking if exists.
1538  *
1539  * It is possible that the origin is not yet created for tablesync
1540  * worker so passing missing_ok = true. This can happen for the states
1541  * before SUBREL_STATE_FINISHEDCOPY.
1542  */
1543  ReplicationOriginNameForLogicalRep(subid, relid, originname,
1544  sizeof(originname));
1545  replorigin_drop_by_name(originname, true, false);
1546  }
1547 
1548  /* Clean up dependencies */
1549  deleteSharedDependencyRecordsFor(SubscriptionRelationId, subid, 0);
1550 
1551  /* Remove any associated relation synchronization states. */
1553 
1554  /* Remove the origin tracking if exists. */
1555  ReplicationOriginNameForLogicalRep(subid, InvalidOid, originname, sizeof(originname));
1556  replorigin_drop_by_name(originname, true, false);
1557 
1558  /*
1559  * If there is no slot associated with the subscription, we can finish
1560  * here.
1561  */
1562  if (!slotname && rstates == NIL)
1563  {
1564  table_close(rel, NoLock);
1565  return;
1566  }
1567 
1568  /*
1569  * Try to acquire the connection necessary for dropping slots.
1570  *
1571  * Note: If the slotname is NONE/NULL then we allow the command to finish
1572  * and users need to manually cleanup the apply and tablesync worker slots
1573  * later.
1574  *
1575  * This has to be at the end because otherwise if there is an error while
1576  * doing the database operations we won't be able to rollback dropped
1577  * slot.
1578  */
1579  load_file("libpqwalreceiver", false);
1580 
1581  wrconn = walrcv_connect(conninfo, true, subname, &err);
1582  if (wrconn == NULL)
1583  {
1584  if (!slotname)
1585  {
1586  /* be tidy */
1587  list_free(rstates);
1588  table_close(rel, NoLock);
1589  return;
1590  }
1591  else
1592  {
1593  ReportSlotConnectionError(rstates, subid, slotname, err);
1594  }
1595  }
1596 
1597  PG_TRY();
1598  {
1599  foreach(lc, rstates)
1600  {
1602  Oid relid = rstate->relid;
1603 
1604  /* Only cleanup resources of tablesync workers */
1605  if (!OidIsValid(relid))
1606  continue;
1607 
1608  /*
1609  * Drop the tablesync slots associated with removed tables.
1610  *
1611  * For SYNCDONE/READY states, the tablesync slot is known to have
1612  * already been dropped by the tablesync worker.
1613  *
1614  * For other states, there is no certainty, maybe the slot does
1615  * not exist yet. Also, if we fail after removing some of the
1616  * slots, next time, it will again try to drop already dropped
1617  * slots and fail. For these reasons, we allow missing_ok = true
1618  * for the drop.
1619  */
1620  if (rstate->state != SUBREL_STATE_SYNCDONE)
1621  {
1622  char syncslotname[NAMEDATALEN] = {0};
1623 
1624  ReplicationSlotNameForTablesync(subid, relid, syncslotname,
1625  sizeof(syncslotname));
1626  ReplicationSlotDropAtPubNode(wrconn, syncslotname, true);
1627  }
1628  }
1629 
1630  list_free(rstates);
1631 
1632  /*
1633  * If there is a slot associated with the subscription, then drop the
1634  * replication slot at the publisher.
1635  */
1636  if (slotname)
1637  ReplicationSlotDropAtPubNode(wrconn, slotname, false);
1638  }
1639  PG_FINALLY();
1640  {
1642  }
1643  PG_END_TRY();
1644 
1645  /*
1646  * Tell the cumulative stats system that the subscription is getting
1647  * dropped.
1648  */
1649  pgstat_drop_subscription(subid);
1650 
1651  table_close(rel, NoLock);
1652 }
1653 
1654 /*
1655  * Drop the replication slot at the publisher node using the replication
1656  * connection.
1657  *
1658  * missing_ok - if true then only issue a LOG message if the slot doesn't
1659  * exist.
1660  */
1661 void
1662 ReplicationSlotDropAtPubNode(WalReceiverConn *wrconn, char *slotname, bool missing_ok)
1663 {
1664  StringInfoData cmd;
1665 
1666  Assert(wrconn);
1667 
1668  load_file("libpqwalreceiver", false);
1669 
1670  initStringInfo(&cmd);
1671  appendStringInfo(&cmd, "DROP_REPLICATION_SLOT %s WAIT", quote_identifier(slotname));
1672 
1673  PG_TRY();
1674  {
1676 
1677  res = walrcv_exec(wrconn, cmd.data, 0, NULL);
1678 
1679  if (res->status == WALRCV_OK_COMMAND)
1680  {
1681  /* NOTICE. Success. */
1682  ereport(NOTICE,
1683  (errmsg("dropped replication slot \"%s\" on publisher",
1684  slotname)));
1685  }
1686  else if (res->status == WALRCV_ERROR &&
1687  missing_ok &&
1688  res->sqlstate == ERRCODE_UNDEFINED_OBJECT)
1689  {
1690  /* LOG. Error, but missing_ok = true. */
1691  ereport(LOG,
1692  (errmsg("could not drop replication slot \"%s\" on publisher: %s",
1693  slotname, res->err)));
1694  }
1695  else
1696  {
1697  /* ERROR. */
1698  ereport(ERROR,
1699  (errcode(ERRCODE_CONNECTION_FAILURE),
1700  errmsg("could not drop replication slot \"%s\" on publisher: %s",
1701  slotname, res->err)));
1702  }
1703 
1705  }
1706  PG_FINALLY();
1707  {
1708  pfree(cmd.data);
1709  }
1710  PG_END_TRY();
1711 }
1712 
1713 /*
1714  * Internal workhorse for changing a subscription owner
1715  */
1716 static void
1718 {
1719  Form_pg_subscription form;
1720 
1721  form = (Form_pg_subscription) GETSTRUCT(tup);
1722 
1723  if (form->subowner == newOwnerId)
1724  return;
1725 
1726  if (!object_ownercheck(SubscriptionRelationId, form->oid, GetUserId()))
1728  NameStr(form->subname));
1729 
1730  /* New owner must be a superuser */
1731  if (!superuser_arg(newOwnerId))
1732  ereport(ERROR,
1733  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1734  errmsg("permission denied to change owner of subscription \"%s\"",
1735  NameStr(form->subname)),
1736  errhint("The owner of a subscription must be a superuser.")));
1737 
1738  form->subowner = newOwnerId;
1739  CatalogTupleUpdate(rel, &tup->t_self, tup);
1740 
1741  /* Update owner dependency reference */
1742  changeDependencyOnOwner(SubscriptionRelationId,
1743  form->oid,
1744  newOwnerId);
1745 
1746  InvokeObjectPostAlterHook(SubscriptionRelationId,
1747  form->oid, 0);
1748 
1749  /* Wake up related background processes to handle this change quickly. */
1752 }
1753 
1754 /*
1755  * Change subscription owner -- by name
1756  */
1758 AlterSubscriptionOwner(const char *name, Oid newOwnerId)
1759 {
1760  Oid subid;
1761  HeapTuple tup;
1762  Relation rel;
1763  ObjectAddress address;
1764  Form_pg_subscription form;
1765 
1766  rel = table_open(SubscriptionRelationId, RowExclusiveLock);
1767 
1770 
1771  if (!HeapTupleIsValid(tup))
1772  ereport(ERROR,
1773  (errcode(ERRCODE_UNDEFINED_OBJECT),
1774  errmsg("subscription \"%s\" does not exist", name)));
1775 
1776  form = (Form_pg_subscription) GETSTRUCT(tup);
1777  subid = form->oid;
1778 
1779  AlterSubscriptionOwner_internal(rel, tup, newOwnerId);
1780 
1781  ObjectAddressSet(address, SubscriptionRelationId, subid);
1782 
1783  heap_freetuple(tup);
1784 
1786 
1787  return address;
1788 }
1789 
1790 /*
1791  * Change subscription owner -- by OID
1792  */
1793 void
1795 {
1796  HeapTuple tup;
1797  Relation rel;
1798 
1799  rel = table_open(SubscriptionRelationId, RowExclusiveLock);
1800 
1802 
1803  if (!HeapTupleIsValid(tup))
1804  ereport(ERROR,
1805  (errcode(ERRCODE_UNDEFINED_OBJECT),
1806  errmsg("subscription with OID %u does not exist", subid)));
1807 
1808  AlterSubscriptionOwner_internal(rel, tup, newOwnerId);
1809 
1810  heap_freetuple(tup);
1811 
1813 }
1814 
1815 /*
1816  * Check and log a warning if the publisher has subscribed to the same table
1817  * from some other publisher. This check is required only if "copy_data = true"
1818  * and "origin = none" for CREATE SUBSCRIPTION and
1819  * ALTER SUBSCRIPTION ... REFRESH statements to notify the user that data
1820  * having origin might have been copied.
1821  *
1822  * This check need not be performed on the tables that are already added
1823  * because incremental sync for those tables will happen through WAL and the
1824  * origin of the data can be identified from the WAL records.
1825  *
1826  * subrel_local_oids contains the list of relation oids that are already
1827  * present on the subscriber.
1828  */
1829 static void
1831  bool copydata, char *origin, Oid *subrel_local_oids,
1832  int subrel_count, char *subname)
1833 {
1835  StringInfoData cmd;
1836  TupleTableSlot *slot;
1837  Oid tableRow[1] = {TEXTOID};
1838  List *publist = NIL;
1839  int i;
1840 
1841  if (!copydata || !origin ||
1842  (pg_strcasecmp(origin, LOGICALREP_ORIGIN_NONE) != 0))
1843  return;
1844 
1845  initStringInfo(&cmd);
1847  "SELECT DISTINCT P.pubname AS pubname\n"
1848  "FROM pg_publication P,\n"
1849  " LATERAL pg_get_publication_tables(P.pubname) GPT\n"
1850  " JOIN pg_subscription_rel PS ON (GPT.relid = PS.srrelid),\n"
1851  " pg_class C JOIN pg_namespace N ON (N.oid = C.relnamespace)\n"
1852  "WHERE C.oid = GPT.relid AND P.pubname IN (");
1853  get_publications_str(publications, &cmd, true);
1854  appendStringInfoString(&cmd, ")\n");
1855 
1856  /*
1857  * In case of ALTER SUBSCRIPTION ... REFRESH, subrel_local_oids contains
1858  * the list of relation oids that are already present on the subscriber.
1859  * This check should be skipped for these tables.
1860  */
1861  for (i = 0; i < subrel_count; i++)
1862  {
1863  Oid relid = subrel_local_oids[i];
1864  char *schemaname = get_namespace_name(get_rel_namespace(relid));
1865  char *tablename = get_rel_name(relid);
1866 
1867  appendStringInfo(&cmd, "AND NOT (N.nspname = '%s' AND C.relname = '%s')\n",
1868  schemaname, tablename);
1869  }
1870 
1871  res = walrcv_exec(wrconn, cmd.data, 1, tableRow);
1872  pfree(cmd.data);
1873 
1874  if (res->status != WALRCV_OK_TUPLES)
1875  ereport(ERROR,
1876  (errcode(ERRCODE_CONNECTION_FAILURE),
1877  errmsg("could not receive list of replicated tables from the publisher: %s",
1878  res->err)));
1879 
1880  /* Process tables. */
1881  slot = MakeSingleTupleTableSlot(res->tupledesc, &TTSOpsMinimalTuple);
1882  while (tuplestore_gettupleslot(res->tuplestore, true, false, slot))
1883  {
1884  char *pubname;
1885  bool isnull;
1886 
1887  pubname = TextDatumGetCString(slot_getattr(slot, 1, &isnull));
1888  Assert(!isnull);
1889 
1890  ExecClearTuple(slot);
1891  publist = list_append_unique(publist, makeString(pubname));
1892  }
1893 
1894  /*
1895  * Log a warning if the publisher has subscribed to the same table from
1896  * some other publisher. We cannot know the origin of data during the
1897  * initial sync. Data origins can be found only from the WAL by looking at
1898  * the origin id.
1899  *
1900  * XXX: For simplicity, we don't check whether the table has any data or
1901  * not. If the table doesn't have any data then we don't need to
1902  * distinguish between data having origin and data not having origin so we
1903  * can avoid logging a warning in that case.
1904  */
1905  if (publist)
1906  {
1907  StringInfo pubnames = makeStringInfo();
1908 
1909  /* Prepare the list of publication(s) for warning message. */
1910  get_publications_str(publist, pubnames, false);
1911  ereport(WARNING,
1912  errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1913  errmsg("subscription \"%s\" requested copy_data with origin = NONE but might copy data that had a different origin",
1914  subname),
1915  errdetail_plural("Subscribed publication %s is subscribing to other publications.",
1916  "Subscribed publications %s are subscribing to other publications.",
1917  list_length(publist), pubnames->data),
1918  errhint("Verify that initial data copied from the publisher tables did not come from other origins."));
1919  }
1920 
1922 
1924 }
1925 
1926 /*
1927  * Get the list of tables which belong to specified publications on the
1928  * publisher connection.
1929  *
1930  * Note that we don't support the case where the column list is different for
1931  * the same table in different publications to avoid sending unwanted column
1932  * information for some of the rows. This can happen when both the column
1933  * list and row filter are specified for different publications.
1934  */
1935 static List *
1937 {
1939  StringInfoData cmd;
1940  TupleTableSlot *slot;
1941  Oid tableRow[3] = {TEXTOID, TEXTOID, NAMEARRAYOID};
1942  List *tablelist = NIL;
1943  bool check_columnlist = (walrcv_server_version(wrconn) >= 150000);
1944 
1945  initStringInfo(&cmd);
1946  appendStringInfoString(&cmd, "SELECT DISTINCT t.schemaname, t.tablename \n");
1947 
1948  /* Get column lists for each relation if the publisher supports it */
1949  if (check_columnlist)
1950  appendStringInfoString(&cmd, ", t.attnames\n");
1951 
1952  appendStringInfoString(&cmd, "FROM pg_catalog.pg_publication_tables t\n"
1953  " WHERE t.pubname IN (");
1954  get_publications_str(publications, &cmd, true);
1955  appendStringInfoChar(&cmd, ')');
1956 
1957  res = walrcv_exec(wrconn, cmd.data, check_columnlist ? 3 : 2, tableRow);
1958  pfree(cmd.data);
1959 
1960  if (res->status != WALRCV_OK_TUPLES)
1961  ereport(ERROR,
1962  (errcode(ERRCODE_CONNECTION_FAILURE),
1963  errmsg("could not receive list of replicated tables from the publisher: %s",
1964  res->err)));
1965 
1966  /* Process tables. */
1967  slot = MakeSingleTupleTableSlot(res->tupledesc, &TTSOpsMinimalTuple);
1968  while (tuplestore_gettupleslot(res->tuplestore, true, false, slot))
1969  {
1970  char *nspname;
1971  char *relname;
1972  bool isnull;
1973  RangeVar *rv;
1974 
1975  nspname = TextDatumGetCString(slot_getattr(slot, 1, &isnull));
1976  Assert(!isnull);
1977  relname = TextDatumGetCString(slot_getattr(slot, 2, &isnull));
1978  Assert(!isnull);
1979 
1980  rv = makeRangeVar(nspname, relname, -1);
1981 
1982  if (check_columnlist && list_member(tablelist, rv))
1983  ereport(ERROR,
1984  errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1985  errmsg("cannot use different column lists for table \"%s.%s\" in different publications",
1986  nspname, relname));
1987  else
1988  tablelist = lappend(tablelist, rv);
1989 
1990  ExecClearTuple(slot);
1991  }
1993 
1995 
1996  return tablelist;
1997 }
1998 
1999 /*
2000  * This is to report the connection failure while dropping replication slots.
2001  * Here, we report the WARNING for all tablesync slots so that user can drop
2002  * them manually, if required.
2003  */
2004 static void
2005 ReportSlotConnectionError(List *rstates, Oid subid, char *slotname, char *err)
2006 {
2007  ListCell *lc;
2008 
2009  foreach(lc, rstates)
2010  {
2012  Oid relid = rstate->relid;
2013 
2014  /* Only cleanup resources of tablesync workers */
2015  if (!OidIsValid(relid))
2016  continue;
2017 
2018  /*
2019  * Caller needs to ensure that relstate doesn't change underneath us.
2020  * See DropSubscription where we get the relstates.
2021  */
2022  if (rstate->state != SUBREL_STATE_SYNCDONE)
2023  {
2024  char syncslotname[NAMEDATALEN] = {0};
2025 
2026  ReplicationSlotNameForTablesync(subid, relid, syncslotname,
2027  sizeof(syncslotname));
2028  elog(WARNING, "could not drop tablesync replication slot \"%s\"",
2029  syncslotname);
2030  }
2031  }
2032 
2033  ereport(ERROR,
2034  (errcode(ERRCODE_CONNECTION_FAILURE),
2035  errmsg("could not connect to publisher when attempting to drop replication slot \"%s\": %s",
2036  slotname, err),
2037  /* translator: %s is an SQL ALTER command */
2038  errhint("Use %s to disassociate the subscription from the slot.",
2039  "ALTER SUBSCRIPTION ... SET (slot_name = NONE)")));
2040 }
2041 
2042 /*
2043  * Check for duplicates in the given list of publications and error out if
2044  * found one. Add publications to datums as text datums, if datums is not
2045  * NULL.
2046  */
2047 static void
2049 {
2050  ListCell *cell;
2051  int j = 0;
2052 
2053  foreach(cell, publist)
2054  {
2055  char *name = strVal(lfirst(cell));
2056  ListCell *pcell;
2057 
2058  foreach(pcell, publist)
2059  {
2060  char *pname = strVal(lfirst(pcell));
2061 
2062  if (pcell == cell)
2063  break;
2064 
2065  if (strcmp(name, pname) == 0)
2066  ereport(ERROR,
2068  errmsg("publication name \"%s\" used more than once",
2069  pname)));
2070  }
2071 
2072  if (datums)
2073  datums[j++] = CStringGetTextDatum(name);
2074  }
2075 }
2076 
2077 /*
2078  * Merge current subscription's publications and user-specified publications
2079  * from ADD/DROP PUBLICATIONS.
2080  *
2081  * If addpub is true, we will add the list of publications into oldpublist.
2082  * Otherwise, we will delete the list of publications from oldpublist. The
2083  * returned list is a copy, oldpublist itself is not changed.
2084  *
2085  * subname is the subscription name, for error messages.
2086  */
2087 static List *
2088 merge_publications(List *oldpublist, List *newpublist, bool addpub, const char *subname)
2089 {
2090  ListCell *lc;
2091 
2092  oldpublist = list_copy(oldpublist);
2093 
2094  check_duplicates_in_publist(newpublist, NULL);
2095 
2096  foreach(lc, newpublist)
2097  {
2098  char *name = strVal(lfirst(lc));
2099  ListCell *lc2;
2100  bool found = false;
2101 
2102  foreach(lc2, oldpublist)
2103  {
2104  char *pubname = strVal(lfirst(lc2));
2105 
2106  if (strcmp(name, pubname) == 0)
2107  {
2108  found = true;
2109  if (addpub)
2110  ereport(ERROR,
2112  errmsg("publication \"%s\" is already in subscription \"%s\"",
2113  name, subname)));
2114  else
2115  oldpublist = foreach_delete_current(oldpublist, lc2);
2116 
2117  break;
2118  }
2119  }
2120 
2121  if (addpub && !found)
2122  oldpublist = lappend(oldpublist, makeString(name));
2123  else if (!addpub && !found)
2124  ereport(ERROR,
2125  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2126  errmsg("publication \"%s\" is not in subscription \"%s\"",
2127  name, subname)));
2128  }
2129 
2130  /*
2131  * XXX Probably no strong reason for this, but for now it's to make ALTER
2132  * SUBSCRIPTION ... DROP PUBLICATION consistent with SET PUBLICATION.
2133  */
2134  if (!oldpublist)
2135  ereport(ERROR,
2136  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2137  errmsg("cannot drop all the publications from a subscription")));
2138 
2139  return oldpublist;
2140 }
2141 
2142 /*
2143  * Extract the streaming mode value from a DefElem. This is like
2144  * defGetBoolean() but also accepts the special value of "parallel".
2145  */
2146 char
2148 {
2149  /*
2150  * If no parameter value given, assume "true" is meant.
2151  */
2152  if (!def->arg)
2153  return LOGICALREP_STREAM_ON;
2154 
2155  /*
2156  * Allow 0, 1, "false", "true", "off", "on" or "parallel".
2157  */
2158  switch (nodeTag(def->arg))
2159  {
2160  case T_Integer:
2161  switch (intVal(def->arg))
2162  {
2163  case 0:
2164  return LOGICALREP_STREAM_OFF;
2165  case 1:
2166  return LOGICALREP_STREAM_ON;
2167  default:
2168  /* otherwise, error out below */
2169  break;
2170  }
2171  break;
2172  default:
2173  {
2174  char *sval = defGetString(def);
2175 
2176  /*
2177  * The set of strings accepted here should match up with the
2178  * grammar's opt_boolean_or_string production.
2179  */
2180  if (pg_strcasecmp(sval, "false") == 0 ||
2181  pg_strcasecmp(sval, "off") == 0)
2182  return LOGICALREP_STREAM_OFF;
2183  if (pg_strcasecmp(sval, "true") == 0 ||
2184  pg_strcasecmp(sval, "on") == 0)
2185  return LOGICALREP_STREAM_ON;
2186  if (pg_strcasecmp(sval, "parallel") == 0)
2188  }
2189  break;
2190  }
2191 
2192  ereport(ERROR,
2193  (errcode(ERRCODE_SYNTAX_ERROR),
2194  errmsg("%s requires a Boolean value or \"parallel\"",
2195  def->defname)));
2196  return LOGICALREP_STREAM_OFF; /* keep compiler quiet */
2197 }
@ ACLCHECK_NOT_OWNER
Definition: acl.h:185
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:2679
bool object_ownercheck(Oid classid, Oid objectid, Oid roleid)
Definition: aclchk.c:3984
ArrayType * construct_array_builtin(Datum *elems, int nelems, Oid elmtype)
Definition: arrayfuncs.c:3363
void LogicalRepWorkersWakeupAtCommit(Oid subid)
Definition: worker.c:4950
void ReplicationOriginNameForLogicalRep(Oid suboid, Oid relid, char *originname, Size szoriginname)
Definition: worker.c:457
static Datum values[MAXATTR]
Definition: bootstrap.c:156
#define CStringGetTextDatum(s)
Definition: builtins.h:94
#define TextDatumGetCString(d)
Definition: builtins.h:95
#define NameStr(name)
Definition: c.h:730
uint32 bits32
Definition: c.h:499
#define OidIsValid(objectId)
Definition: c.h:759
Oid GetNewOidWithIndex(Relation relation, Oid indexId, AttrNumber oidcolumn)
Definition: catalog.c:393
bool defGetBoolean(DefElem *def)
Definition: define.c:108
char * defGetString(DefElem *def)
Definition: define.c:49
void errorConflictingDefElem(DefElem *defel, ParseState *pstate)
Definition: define.c:385
void load_file(const char *filename, bool restricted)
Definition: dfmgr.c:144
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:1179
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1156
int errdetail_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:1294
int errhint(const char *fmt,...)
Definition: elog.c:1316
int errcode(int sqlerrcode)
Definition: elog.c:858
int errmsg(const char *fmt,...)
Definition: elog.c:1069
#define LOG
Definition: elog.h:31
#define PG_TRY(...)
Definition: elog.h:370
#define WARNING
Definition: elog.h:36
#define PG_END_TRY(...)
Definition: elog.h:395
#define DEBUG1
Definition: elog.h:30
#define ERROR
Definition: elog.h:39
#define NOTICE
Definition: elog.h:35
#define PG_FINALLY(...)
Definition: elog.h:387
#define ereport(elevel,...)
Definition: elog.h:149
const char * name
Definition: encode.c:571
void err(int eval, const char *fmt,...)
Definition: err.c:43
void EventTriggerSQLDropAddObject(const ObjectAddress *object, bool original, bool normal)
void CheckSubscriptionRelkind(char relkind, const char *nspname, const char *relname)
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1254
const TupleTableSlotOps TTSOpsMinimalTuple
Definition: execTuples.c:85
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1238
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:642
Oid MyDatabaseId
Definition: globals.c:89
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:3284
@ GUC_ACTION_SET
Definition: guc.h:197
@ PGC_S_TEST
Definition: guc.h:121
@ PGC_BACKEND
Definition: guc.h:73
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:1113
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:653
#define stmt
Definition: indent_codes.h:59
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:221
void CatalogTupleDelete(Relation heapRel, ItemPointer tid)
Definition: indexing.c:350
int j
Definition: isn.c:74
int i
Definition: isn.c:73
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
List * logicalrep_workers_find(Oid subid, bool only_running)
Definition: launcher.c:281
void logicalrep_worker_stop(Oid subid, Oid relid)
Definition: launcher.c:594
void ApplyLauncherWakeupAtCommit(void)
Definition: launcher.c:1061
void ApplyLauncherForgetWorkerStartTime(Oid subid)
Definition: launcher.c:1031
Assert(fmt[strlen(fmt) - 1] !='\n')
List * lappend(List *list, void *datum)
Definition: list.c:338
List * list_copy(const List *oldlist)
Definition: list.c:1572
List * list_append_unique(List *list, void *datum)
Definition: list.c:1342
List * list_delete(List *list, void *datum)
Definition: list.c:852
void list_free(List *list)
Definition: list.c:1545
bool list_member(const List *list, const void *datum)
Definition: list.c:660
void LockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:1046
#define NoLock
Definition: lockdefs.h:34
#define AccessExclusiveLock
Definition: lockdefs.h:43
#define AccessShareLock
Definition: lockdefs.h:36
#define RowExclusiveLock
Definition: lockdefs.h:38
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3331
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1985
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1934
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1910
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1195
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
@ LW_SHARED
Definition: lwlock.h:116
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:424
char * pstrdup(const char *in)
Definition: mcxt.c:1624
void pfree(void *pointer)
Definition: mcxt.c:1436
MemoryContext CurrentMemoryContext
Definition: mcxt.c:135
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:387
void * palloc(Size size)
Definition: mcxt.c:1210
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:153
Oid GetUserId(void)
Definition: miscinit.c:510
Datum namein(PG_FUNCTION_ARGS)
Definition: name.c:48
#define RangeVarGetRelid(relation, lockmode, missing_ok)
Definition: namespace.h:79
#define nodeTag(nodeptr)
Definition: nodes.h:133
#define InvokeObjectPostCreateHook(classId, objectId, subId)
Definition: objectaccess.h:173
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:197
#define InvokeObjectDropHook(classId, objectId, subId)
Definition: objectaccess.h:182
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
int oid_cmp(const void *p1, const void *p2)
Definition: oid.c:257
RepOriginId replorigin_by_name(const char *roname, bool missing_ok)
Definition: origin.c:221
RepOriginId replorigin_create(const char *roname)
Definition: origin.c:252
XLogRecPtr replorigin_get_progress(RepOriginId node, bool flush)
Definition: origin.c:1014
void replorigin_drop_by_name(const char *name, bool missing_ok, bool nowait)
Definition: origin.c:411
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:138
@ ALTER_SUBSCRIPTION_ENABLED
Definition: parsenodes.h:3923
@ ALTER_SUBSCRIPTION_DROP_PUBLICATION
Definition: parsenodes.h:3921
@ ALTER_SUBSCRIPTION_SET_PUBLICATION
Definition: parsenodes.h:3919
@ ALTER_SUBSCRIPTION_REFRESH
Definition: parsenodes.h:3922
@ ALTER_SUBSCRIPTION_SKIP
Definition: parsenodes.h:3924
@ ALTER_SUBSCRIPTION_OPTIONS
Definition: parsenodes.h:3917
@ ALTER_SUBSCRIPTION_CONNECTION
Definition: parsenodes.h:3918
@ ALTER_SUBSCRIPTION_ADD_PUBLICATION
Definition: parsenodes.h:3920
@ OBJECT_SUBSCRIPTION
Definition: parsenodes.h:2013
static AmcheckOptions opts
Definition: pg_amcheck.c:110
NameData relname
Definition: pg_class.h:38
#define NAMEDATALEN
#define lfirst(lc)
Definition: pg_list.h:172
static int list_length(const List *l)
Definition: pg_list.h:152
#define NIL
Definition: pg_list.h:68
#define foreach_delete_current(lst, cell)
Definition: pg_list.h:390
Datum pg_lsn_in(PG_FUNCTION_ARGS)
Definition: pg_lsn.c:64
static Datum LSNGetDatum(XLogRecPtr X)
Definition: pg_lsn.h:28
static XLogRecPtr DatumGetLSN(Datum X)
Definition: pg_lsn.h:22
void changeDependencyOnOwner(Oid classId, Oid objectId, Oid newOwnerId)
Definition: pg_shdepend.c:313
void deleteSharedDependencyRecordsFor(Oid classId, Oid objectId, int32 objectSubId)
Definition: pg_shdepend.c:1002
void recordDependencyOnOwner(Oid classId, Oid objectId, Oid owner)
Definition: pg_shdepend.c:165
void RemoveSubscriptionRel(Oid subid, Oid relid)
List * GetSubscriptionRelations(Oid subid, bool not_ready)
char GetSubscriptionRelState(Oid subid, Oid relid, XLogRecPtr *sublsn)
Subscription * GetSubscription(Oid subid, bool missing_ok)
void AddSubscriptionRelState(Oid subid, Oid relid, char state, XLogRecPtr sublsn)
#define LOGICALREP_ORIGIN_NONE
#define LOGICALREP_STREAM_ON
#define LOGICALREP_ORIGIN_ANY
#define LOGICALREP_STREAM_OFF
#define LOGICALREP_STREAM_PARALLEL
NameData subname
#define LOGICALREP_TWOPHASE_STATE_DISABLED
#define LOGICALREP_TWOPHASE_STATE_PENDING
#define LOGICALREP_TWOPHASE_STATE_ENABLED
FormData_pg_subscription * Form_pg_subscription
void pgstat_drop_subscription(Oid subid)
void pgstat_create_subscription(Oid subid)
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
#define qsort(a, b, c, d)
Definition: port.h:445
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:322
static Name DatumGetName(Datum X)
Definition: postgres.h:360
uintptr_t Datum
Definition: postgres.h:64
static Datum BoolGetDatum(bool X)
Definition: postgres.h:102
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:252
static Datum CStringGetDatum(const char *X)
Definition: postgres.h:350
static Datum CharGetDatum(char X)
Definition: postgres.h:122
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
char * quote_literal_cstr(const char *rawstr)
Definition: quote.c:103
Datum quote_literal(PG_FUNCTION_ARGS)
Definition: quote.c:78
#define RelationGetDescr(relation)
Definition: rel.h:527
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:11551
bool ReplicationSlotValidateName(const char *name, int elevel)
Definition: slot.c:198
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:32
StringInfo makeStringInfo(void)
Definition: stringinfo.c:41
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
char * defname
Definition: parsenodes.h:810
Node * arg
Definition: parsenodes.h:811
ItemPointerData t_self
Definition: htup.h:65
Definition: pg_list.h:54
char * relname
Definition: primnodes.h:74
char * schemaname
Definition: primnodes.h:71
bool copy_data
bits32 specified_opts
bool disableonerr
bool create_slot
char * synchronous_commit
char streaming
char * origin
char * slot_name
XLogRecPtr lsn
Definition: regguts.h:318
struct SubOpts SubOpts
void DropSubscription(DropSubscriptionStmt *stmt, bool isTopLevel)
#define SUBOPT_STREAMING
char defGetStreamingMode(DefElem *def)
#define SUBOPT_CREATE_SLOT
ObjectAddress CreateSubscription(ParseState *pstate, CreateSubscriptionStmt *stmt, bool isTopLevel)
#define SUBOPT_SYNCHRONOUS_COMMIT
#define SUBOPT_ENABLED
static void check_duplicates_in_publist(List *publist, Datum *datums)
#define SUBOPT_ORIGIN
static Datum publicationListToArray(List *publist)
static void get_publications_str(List *publications, StringInfo dest, bool quote_literal)
static void parse_subscription_options(ParseState *pstate, List *stmt_options, bits32 supported_opts, SubOpts *opts)
static void check_publications(WalReceiverConn *wrconn, List *publications)
#define SUBOPT_SLOT_NAME
#define SUBOPT_COPY_DATA
#define SUBOPT_TWOPHASE_COMMIT
static void AlterSubscription_refresh(Subscription *sub, bool copy_data, List *validate_publications)
static void ReportSlotConnectionError(List *rstates, Oid subid, char *slotname, char *err)
#define SUBOPT_DISABLE_ON_ERR
static void AlterSubscriptionOwner_internal(Relation rel, HeapTuple tup, Oid newOwnerId)
ObjectAddress AlterSubscriptionOwner(const char *name, Oid newOwnerId)
static void check_publications_origin(WalReceiverConn *wrconn, List *publications, bool copydata, char *origin, Oid *subrel_local_oids, int subrel_count, char *subname)
void ReplicationSlotDropAtPubNode(WalReceiverConn *wrconn, char *slotname, bool missing_ok)
void AlterSubscriptionOwner_oid(Oid subid, Oid newOwnerId)
#define SUBOPT_LSN
static List * merge_publications(List *oldpublist, List *newpublist, bool addpub, const char *subname)
#define SUBOPT_BINARY
#define IsSet(val, bits)
#define SUBOPT_REFRESH
static List * fetch_table_list(WalReceiverConn *wrconn, List *publications)
#define SUBOPT_CONNECT
ObjectAddress AlterSubscription(ParseState *pstate, AlterSubscriptionStmt *stmt, bool isTopLevel)
bool superuser_arg(Oid roleid)
Definition: superuser.c:56
bool superuser(void)
Definition: superuser.c:46
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:865
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1078
HeapTuple SearchSysCache2(int cacheId, Datum key1, Datum key2)
Definition: syscache.c:828
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:179
#define SearchSysCacheCopy2(cacheId, key1, key2)
Definition: syscache.h:181
@ SUBSCRIPTIONNAME
Definition: syscache.h:98
@ SUBSCRIPTIONOID
Definition: syscache.h:99
#define GetSysCacheOid2(cacheId, oidcol, key1, key2)
Definition: syscache.h:199
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:40
void ReplicationSlotNameForTablesync(Oid suboid, Oid relid, char *syncslotname, Size szslot)
Definition: tablesync.c:1213
void UpdateTwoPhaseState(Oid suboid, char new_state)
Definition: tablesync.c:1583
bool tuplestore_gettupleslot(Tuplestorestate *state, bool forward, bool copy, TupleTableSlot *slot)
Definition: tuplestore.c:1078
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:433
static Datum slot_getattr(TupleTableSlot *slot, int attnum, bool *isnull)
Definition: tuptable.h:389
String * makeString(char *str)
Definition: value.c:63
#define intVal(v)
Definition: value.h:79
#define strVal(v)
Definition: value.h:82
static WalReceiverConn * wrconn
Definition: walreceiver.c:95
#define walrcv_create_slot(conn, slotname, temporary, two_phase, snapshot_action, lsn)
Definition: walreceiver.h:430
#define walrcv_check_conninfo(conninfo)
Definition: walreceiver.h:410
#define walrcv_connect(conninfo, logical, appname, err)
Definition: walreceiver.h:408
@ WALRCV_OK_COMMAND
Definition: walreceiver.h:205
@ WALRCV_ERROR
Definition: walreceiver.h:204
@ WALRCV_OK_TUPLES
Definition: walreceiver.h:207
static void walrcv_clear_result(WalRcvExecResult *walres)
Definition: walreceiver.h:440
#define walrcv_server_version(conn)
Definition: walreceiver.h:418
#define walrcv_exec(conn, exec, nRetTypes, retTypes)
Definition: walreceiver.h:434
#define walrcv_disconnect(conn)
Definition: walreceiver.h:436
@ CRS_NOEXPORT_SNAPSHOT
Definition: walsender.h:23
void PreventInTransactionBlock(bool isTopLevel, const char *stmtType)
Definition: xact.c:3488
#define LSN_FORMAT_ARGS(lsn)
Definition: xlogdefs.h:43
#define XLogRecPtrIsInvalid(r)
Definition: xlogdefs.h:29
uint16 RepOriginId
Definition: xlogdefs.h:65
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28