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