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