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