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