PostgreSQL Source Code  git master
subscriptioncmds.c File Reference
Include dependency graph for subscriptioncmds.c:

Go to the source code of this file.

Data Structures

struct  SubOpts
 

Macros

#define SUBOPT_CONNECT   0x00000001
 
#define SUBOPT_ENABLED   0x00000002
 
#define SUBOPT_CREATE_SLOT   0x00000004
 
#define SUBOPT_SLOT_NAME   0x00000008
 
#define SUBOPT_COPY_DATA   0x00000010
 
#define SUBOPT_SYNCHRONOUS_COMMIT   0x00000020
 
#define SUBOPT_REFRESH   0x00000040
 
#define SUBOPT_BINARY   0x00000080
 
#define SUBOPT_STREAMING   0x00000100
 
#define SUBOPT_TWOPHASE_COMMIT   0x00000200
 
#define IsSet(val, bits)   (((val) & (bits)) == (bits))
 

Typedefs

typedef struct SubOpts SubOpts
 

Functions

static Listfetch_table_list (WalReceiverConn *wrconn, List *publications)
 
static void check_duplicates_in_publist (List *publist, Datum *datums)
 
static Listmerge_publications (List *oldpublist, List *newpublist, bool addpub, const char *subname)
 
static void ReportSlotConnectionError (List *rstates, Oid subid, char *slotname, char *err)
 
static void parse_subscription_options (ParseState *pstate, List *stmt_options, bits32 supported_opts, SubOpts *opts)
 
static Datum publicationListToArray (List *publist)
 
ObjectAddress CreateSubscription (ParseState *pstate, CreateSubscriptionStmt *stmt, bool isTopLevel)
 
static void AlterSubscription_refresh (Subscription *sub, bool copy_data)
 
ObjectAddress AlterSubscription (ParseState *pstate, AlterSubscriptionStmt *stmt, bool isTopLevel)
 
void DropSubscription (DropSubscriptionStmt *stmt, bool isTopLevel)
 
void ReplicationSlotDropAtPubNode (WalReceiverConn *wrconn, char *slotname, bool missing_ok)
 
static void AlterSubscriptionOwner_internal (Relation rel, HeapTuple tup, Oid newOwnerId)
 
ObjectAddress AlterSubscriptionOwner (const char *name, Oid newOwnerId)
 
void AlterSubscriptionOwner_oid (Oid subid, Oid newOwnerId)
 

Macro Definition Documentation

◆ IsSet

#define IsSet (   val,
  bits 
)    (((val) & (bits)) == (bits))

◆ SUBOPT_BINARY

#define SUBOPT_BINARY   0x00000080

◆ SUBOPT_CONNECT

#define SUBOPT_CONNECT   0x00000001

Definition at line 53 of file subscriptioncmds.c.

Referenced by CreateSubscription(), and parse_subscription_options().

◆ SUBOPT_COPY_DATA

#define SUBOPT_COPY_DATA   0x00000010

◆ SUBOPT_CREATE_SLOT

#define SUBOPT_CREATE_SLOT   0x00000004

Definition at line 55 of file subscriptioncmds.c.

Referenced by CreateSubscription(), and parse_subscription_options().

◆ SUBOPT_ENABLED

#define SUBOPT_ENABLED   0x00000002

◆ SUBOPT_REFRESH

#define SUBOPT_REFRESH   0x00000040

Definition at line 59 of file subscriptioncmds.c.

Referenced by AlterSubscription(), and parse_subscription_options().

◆ SUBOPT_SLOT_NAME

#define SUBOPT_SLOT_NAME   0x00000008

◆ SUBOPT_STREAMING

#define SUBOPT_STREAMING   0x00000100

◆ SUBOPT_SYNCHRONOUS_COMMIT

#define SUBOPT_SYNCHRONOUS_COMMIT   0x00000020

◆ SUBOPT_TWOPHASE_COMMIT

#define SUBOPT_TWOPHASE_COMMIT   0x00000200

Definition at line 62 of file subscriptioncmds.c.

Referenced by CreateSubscription(), and parse_subscription_options().

Typedef Documentation

◆ SubOpts

typedef struct SubOpts SubOpts

Function Documentation

◆ AlterSubscription()

ObjectAddress AlterSubscription ( ParseState pstate,
AlterSubscriptionStmt stmt,
bool  isTopLevel 
)

Definition at line 840 of file subscriptioncmds.c.

References AccessExclusiveLock, aclcheck_error(), ACLCHECK_NOT_OWNER, ALTER_SUBSCRIPTION_ADD_PUBLICATION, ALTER_SUBSCRIPTION_CONNECTION, ALTER_SUBSCRIPTION_DROP_PUBLICATION, ALTER_SUBSCRIPTION_ENABLED, ALTER_SUBSCRIPTION_OPTIONS, ALTER_SUBSCRIPTION_REFRESH, ALTER_SUBSCRIPTION_SET_PUBLICATION, AlterSubscription_refresh(), ApplyLauncherWakeupAtCommit(), Assert, SubOpts::binary, BoolGetDatum, CatalogTupleUpdate(), AlterSubscriptionStmt::conninfo, SubOpts::copy_data, CStringGetDatum, CStringGetTextDatum, DirectFunctionCall1, elog, SubOpts::enabled, Subscription::enabled, ereport, errcode(), errhint(), errmsg(), ERROR, GETSTRUCT, GetSubscription(), GetUserId(), heap_freetuple(), heap_modify_tuple(), HeapTupleIsValid, InvokeObjectPostAlterHook, IsSet, AlterSubscriptionStmt::kind, load_file(), LockSharedObject(), LOGICALREP_TWOPHASE_STATE_DISABLED, LOGICALREP_TWOPHASE_STATE_ENABLED, merge_publications(), MyDatabaseId, namein(), OBJECT_SUBSCRIPTION, ObjectAddressSet, AlterSubscriptionStmt::options, opts, parse_subscription_options(), pg_subscription_ownercheck(), PreventInTransactionBlock(), AlterSubscriptionStmt::publication, publicationListToArray(), Subscription::publications, SubOpts::refresh, RelationGetDescr, RowExclusiveLock, SearchSysCacheCopy2, SubOpts::slot_name, Subscription::slotname, SubOpts::specified_opts, SubOpts::streaming, AlterSubscriptionStmt::subname, SUBOPT_BINARY, SUBOPT_COPY_DATA, SUBOPT_ENABLED, SUBOPT_REFRESH, SUBOPT_SLOT_NAME, SUBOPT_STREAMING, SUBOPT_SYNCHRONOUS_COMMIT, SUBSCRIPTIONNAME, SubOpts::synchronous_commit, HeapTupleData::t_self, table_close(), table_open(), Subscription::twophasestate, values, and walrcv_check_conninfo.

Referenced by ProcessUtilitySlow().

842 {
843  Relation rel;
844  ObjectAddress myself;
845  bool nulls[Natts_pg_subscription];
846  bool replaces[Natts_pg_subscription];
847  Datum values[Natts_pg_subscription];
848  HeapTuple tup;
849  Oid subid;
850  bool update_tuple = false;
851  Subscription *sub;
853  bits32 supported_opts;
854  SubOpts opts = {0};
855 
856  rel = table_open(SubscriptionRelationId, RowExclusiveLock);
857 
858  /* Fetch the existing tuple. */
860  CStringGetDatum(stmt->subname));
861 
862  if (!HeapTupleIsValid(tup))
863  ereport(ERROR,
864  (errcode(ERRCODE_UNDEFINED_OBJECT),
865  errmsg("subscription \"%s\" does not exist",
866  stmt->subname)));
867 
868  form = (Form_pg_subscription) GETSTRUCT(tup);
869  subid = form->oid;
870 
871  /* must be owner */
872  if (!pg_subscription_ownercheck(subid, GetUserId()))
874  stmt->subname);
875 
876  sub = GetSubscription(subid, false);
877 
878  /* Lock the subscription so nobody else can do anything with it. */
879  LockSharedObject(SubscriptionRelationId, subid, 0, AccessExclusiveLock);
880 
881  /* Form a new tuple. */
882  memset(values, 0, sizeof(values));
883  memset(nulls, false, sizeof(nulls));
884  memset(replaces, false, sizeof(replaces));
885 
886  switch (stmt->kind)
887  {
889  {
890  supported_opts = (SUBOPT_SLOT_NAME |
893 
894  parse_subscription_options(pstate, stmt->options,
895  supported_opts, &opts);
896 
898  {
899  /*
900  * The subscription must be disabled to allow slot_name as
901  * 'none', otherwise, the apply worker will repeatedly try
902  * to stream the data using that slot_name which neither
903  * exists on the publisher nor the user will be allowed to
904  * create it.
905  */
906  if (sub->enabled && !opts.slot_name)
907  ereport(ERROR,
908  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
909  errmsg("cannot set %s for enabled subscription",
910  "slot_name = NONE")));
911 
912  if (opts.slot_name)
913  values[Anum_pg_subscription_subslotname - 1] =
915  else
916  nulls[Anum_pg_subscription_subslotname - 1] = true;
917  replaces[Anum_pg_subscription_subslotname - 1] = true;
918  }
919 
920  if (opts.synchronous_commit)
921  {
922  values[Anum_pg_subscription_subsynccommit - 1] =
924  replaces[Anum_pg_subscription_subsynccommit - 1] = true;
925  }
926 
928  {
929  values[Anum_pg_subscription_subbinary - 1] =
930  BoolGetDatum(opts.binary);
931  replaces[Anum_pg_subscription_subbinary - 1] = true;
932  }
933 
935  {
937  ereport(ERROR,
938  (errcode(ERRCODE_SYNTAX_ERROR),
939  errmsg("cannot set %s for two-phase enabled subscription",
940  "streaming = true")));
941 
942  values[Anum_pg_subscription_substream - 1] =
943  BoolGetDatum(opts.streaming);
944  replaces[Anum_pg_subscription_substream - 1] = true;
945  }
946 
947  update_tuple = true;
948  break;
949  }
950 
952  {
953  parse_subscription_options(pstate, stmt->options,
954  SUBOPT_ENABLED, &opts);
956 
957  if (!sub->slotname && opts.enabled)
958  ereport(ERROR,
959  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
960  errmsg("cannot enable subscription that does not have a slot name")));
961 
962  values[Anum_pg_subscription_subenabled - 1] =
963  BoolGetDatum(opts.enabled);
964  replaces[Anum_pg_subscription_subenabled - 1] = true;
965 
966  if (opts.enabled)
968 
969  update_tuple = true;
970  break;
971  }
972 
974  /* Load the library providing us libpq calls. */
975  load_file("libpqwalreceiver", false);
976  /* Check the connection info string. */
978 
979  values[Anum_pg_subscription_subconninfo - 1] =
981  replaces[Anum_pg_subscription_subconninfo - 1] = true;
982  update_tuple = true;
983  break;
984 
986  {
987  supported_opts = SUBOPT_COPY_DATA | SUBOPT_REFRESH;
988  parse_subscription_options(pstate, stmt->options,
989  supported_opts, &opts);
990 
991  values[Anum_pg_subscription_subpublications - 1] =
993  replaces[Anum_pg_subscription_subpublications - 1] = true;
994 
995  update_tuple = true;
996 
997  /* Refresh if user asked us to. */
998  if (opts.refresh)
999  {
1000  if (!sub->enabled)
1001  ereport(ERROR,
1002  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1003  errmsg("ALTER SUBSCRIPTION with refresh is not allowed for disabled subscriptions"),
1004  errhint("Use ALTER SUBSCRIPTION ... SET PUBLICATION ... WITH (refresh = false).")));
1005 
1006  /*
1007  * See ALTER_SUBSCRIPTION_REFRESH for details why this is
1008  * not allowed.
1009  */
1011  ereport(ERROR,
1012  (errcode(ERRCODE_SYNTAX_ERROR),
1013  errmsg("ALTER SUBSCRIPTION with refresh and copy_data is not allowed when two_phase is enabled"),
1014  errhint("Use ALTER SUBSCRIPTION ...SET PUBLICATION with refresh = false, or with copy_data = false"
1015  ", or use DROP/CREATE SUBSCRIPTION.")));
1016 
1017  PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION with refresh");
1018 
1019  /* Make sure refresh sees the new list of publications. */
1020  sub->publications = stmt->publication;
1021 
1023  }
1024 
1025  break;
1026  }
1027 
1030  {
1031  List *publist;
1032  bool isadd = stmt->kind == ALTER_SUBSCRIPTION_ADD_PUBLICATION;
1033 
1034  supported_opts = SUBOPT_REFRESH;
1035  if (isadd)
1036  supported_opts |= SUBOPT_COPY_DATA;
1037 
1038  parse_subscription_options(pstate, stmt->options,
1039  supported_opts, &opts);
1040 
1041  publist = merge_publications(sub->publications, stmt->publication, isadd, stmt->subname);
1042  values[Anum_pg_subscription_subpublications - 1] =
1043  publicationListToArray(publist);
1044  replaces[Anum_pg_subscription_subpublications - 1] = true;
1045 
1046  update_tuple = true;
1047 
1048  /* Refresh if user asked us to. */
1049  if (opts.refresh)
1050  {
1051  if (!sub->enabled)
1052  ereport(ERROR,
1053  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1054  errmsg("ALTER SUBSCRIPTION with refresh is not allowed for disabled subscriptions"),
1055  errhint("Use ALTER SUBSCRIPTION ... SET PUBLICATION ... WITH (refresh = false).")));
1056 
1057  /*
1058  * See ALTER_SUBSCRIPTION_REFRESH for details why this is
1059  * not allowed.
1060  */
1062  ereport(ERROR,
1063  (errcode(ERRCODE_SYNTAX_ERROR),
1064  errmsg("ALTER SUBSCRIPTION with refresh and copy_data is not allowed when two_phase is enabled"),
1065  errhint("Use ALTER SUBSCRIPTION ...SET PUBLICATION with refresh = false, or with copy_data = false"
1066  ", or use DROP/CREATE SUBSCRIPTION.")));
1067 
1068  PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION with refresh");
1069 
1070  /* Only refresh the added/dropped list of publications. */
1071  sub->publications = stmt->publication;
1072 
1074  }
1075 
1076  break;
1077  }
1078 
1080  {
1081  if (!sub->enabled)
1082  ereport(ERROR,
1083  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1084  errmsg("ALTER SUBSCRIPTION ... REFRESH is not allowed for disabled subscriptions")));
1085 
1086  parse_subscription_options(pstate, stmt->options,
1087  SUBOPT_COPY_DATA, &opts);
1088 
1089  /*
1090  * The subscription option "two_phase" requires that
1091  * replication has passed the initial table synchronization
1092  * phase before the two_phase becomes properly enabled.
1093  *
1094  * But, having reached this two-phase commit "enabled" state
1095  * we must not allow any subsequent table initialization to
1096  * occur. So the ALTER SUBSCRIPTION ... REFRESH is disallowed
1097  * when the user had requested two_phase = on mode.
1098  *
1099  * The exception to this restriction is when copy_data =
1100  * false, because when copy_data is false the tablesync will
1101  * start already in READY state and will exit directly without
1102  * doing anything.
1103  *
1104  * For more details see comments atop worker.c.
1105  */
1107  ereport(ERROR,
1108  (errcode(ERRCODE_SYNTAX_ERROR),
1109  errmsg("ALTER SUBSCRIPTION ... REFRESH with copy_data is not allowed when two_phase is enabled"),
1110  errhint("Use ALTER SUBSCRIPTION ... REFRESH with copy_data = false"
1111  ", or use DROP/CREATE SUBSCRIPTION.")));
1112 
1113  PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION ... REFRESH");
1114 
1116 
1117  break;
1118  }
1119 
1120  default:
1121  elog(ERROR, "unrecognized ALTER SUBSCRIPTION kind %d",
1122  stmt->kind);
1123  }
1124 
1125  /* Update the catalog if needed. */
1126  if (update_tuple)
1127  {
1128  tup = heap_modify_tuple(tup, RelationGetDescr(rel), values, nulls,
1129  replaces);
1130 
1131  CatalogTupleUpdate(rel, &tup->t_self, tup);
1132 
1133  heap_freetuple(tup);
1134  }
1135 
1137 
1138  ObjectAddressSet(myself, SubscriptionRelationId, subid);
1139 
1140  InvokeObjectPostAlterHook(SubscriptionRelationId, subid, 0);
1141 
1142  return myself;
1143 }
Datum namein(PG_FUNCTION_ARGS)
Definition: name.c:48
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
int errhint(const char *fmt,...)
Definition: elog.c:1156
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
bool copy_data
#define RelationGetDescr(relation)
Definition: rel.h:503
Oid GetUserId(void)
Definition: miscinit.c:478
#define LOGICALREP_TWOPHASE_STATE_DISABLED
#define walrcv_check_conninfo(conninfo)
Definition: walreceiver.h:406
bits32 specified_opts
int errcode(int sqlerrcode)
Definition: elog.c:698
#define SUBOPT_ENABLED
static Datum publicationListToArray(List *publist)
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:626
FormData_pg_subscription * Form_pg_subscription
#define SUBOPT_SYNCHRONOUS_COMMIT
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
static void parse_subscription_options(ParseState *pstate, List *stmt_options, bits32 supported_opts, SubOpts *opts)
#define SUBOPT_STREAMING
#define LOGICALREP_TWOPHASE_STATE_ENABLED
Subscription * GetSubscription(Oid subid, bool missing_ok)
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3308
bool streaming
#define ERROR
Definition: elog.h:46
#define SUBOPT_BINARY
ItemPointerData t_self
Definition: htup.h:65
AlterSubscriptionType kind
Definition: parsenodes.h:3674
#define SUBOPT_REFRESH
#define RowExclusiveLock
Definition: lockdefs.h:38
#define CStringGetDatum(X)
Definition: postgres.h:622
void PreventInTransactionBlock(bool isTopLevel, const char *stmtType)
Definition: xact.c:3379
char * slot_name
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:175
static AmcheckOptions opts
Definition: pg_amcheck.c:111
uintptr_t Datum
Definition: postgres.h:411
Oid MyDatabaseId
Definition: globals.c:88
void LockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:1017
#define BoolGetDatum(X)
Definition: postgres.h:446
#define ereport(elevel,...)
Definition: elog.h:157
uint32 bits32
Definition: c.h:450
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define SUBOPT_COPY_DATA
#define Assert(condition)
Definition: c.h:804
void load_file(const char *filename, bool restricted)
Definition: dfmgr.c:146
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
#define SUBOPT_SLOT_NAME
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
static Datum values[MAXATTR]
Definition: bootstrap.c:166
#define AccessExclusiveLock
Definition: lockdefs.h:45
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define elog(elevel,...)
Definition: elog.h:232
#define CStringGetTextDatum(s)
Definition: builtins.h:82
void ApplyLauncherWakeupAtCommit(void)
Definition: launcher.c:780
#define SearchSysCacheCopy2(cacheId, key1, key2)
Definition: syscache.h:177
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:1113
Definition: pg_list.h:50
#define IsSet(val, bits)
char * synchronous_commit
static void AlterSubscription_refresh(Subscription *sub, bool copy_data)
static List * merge_publications(List *oldpublist, List *newpublist, bool addpub, const char *subname)
bool pg_subscription_ownercheck(Oid sub_oid, Oid roleid)
Definition: aclchk.c:5382

◆ AlterSubscription_refresh()

static void AlterSubscription_refresh ( Subscription sub,
bool  copy_data 
)
static

Definition at line 628 of file subscriptioncmds.c.

References AccessExclusiveLock, AccessShareLock, AddSubscriptionRelState(), CheckSubscriptionRelkind(), Subscription::conninfo, DEBUG1, ereport, errcode(), errmsg(), errmsg_internal(), ERROR, fetch_table_list(), get_namespace_name(), get_rel_name(), get_rel_namespace(), get_rel_relkind(), GetSubscriptionRelations(), GetSubscriptionRelState(), InvalidXLogRecPtr, lfirst, list_length(), load_file(), logicalrep_worker_stop(), Subscription::name, NAMEDATALEN, NoLock, Subscription::oid, oid_cmp(), palloc(), PG_END_TRY, PG_FINALLY, PG_TRY, Subscription::publications, qsort, RangeVarGetRelid, SubscriptionRelState::relid, RangeVar::relname, RemoveSubscriptionRel(), ReplicationOriginNameForTablesync(), ReplicationSlotDropAtPubNode(), ReplicationSlotNameForTablesync(), replorigin_drop_by_name(), RangeVar::schemaname, table_close(), table_open(), walrcv_connect, walrcv_disconnect, and wrconn.

Referenced by AlterSubscription().

629 {
630  char *err;
631  List *pubrel_names;
632  List *subrel_states;
633  Oid *subrel_local_oids;
634  Oid *pubrel_local_oids;
635  ListCell *lc;
636  int off;
637  int remove_rel_len;
638  Relation rel = NULL;
639  typedef struct SubRemoveRels
640  {
641  Oid relid;
642  char state;
643  } SubRemoveRels;
644  SubRemoveRels *sub_remove_rels;
646 
647  /* Load the library providing us libpq calls. */
648  load_file("libpqwalreceiver", false);
649 
650  /* Try to connect to the publisher. */
651  wrconn = walrcv_connect(sub->conninfo, true, sub->name, &err);
652  if (!wrconn)
653  ereport(ERROR,
654  (errcode(ERRCODE_CONNECTION_FAILURE),
655  errmsg("could not connect to the publisher: %s", err)));
656 
657  PG_TRY();
658  {
659  /* Get the table list from publisher. */
660  pubrel_names = fetch_table_list(wrconn, sub->publications);
661 
662  /* Get local table list. */
663  subrel_states = GetSubscriptionRelations(sub->oid);
664 
665  /*
666  * Build qsorted array of local table oids for faster lookup. This can
667  * potentially contain all tables in the database so speed of lookup
668  * is important.
669  */
670  subrel_local_oids = palloc(list_length(subrel_states) * sizeof(Oid));
671  off = 0;
672  foreach(lc, subrel_states)
673  {
675 
676  subrel_local_oids[off++] = relstate->relid;
677  }
678  qsort(subrel_local_oids, list_length(subrel_states),
679  sizeof(Oid), oid_cmp);
680 
681  /*
682  * Rels that we want to remove from subscription and drop any slots
683  * and origins corresponding to them.
684  */
685  sub_remove_rels = palloc(list_length(subrel_states) * sizeof(SubRemoveRels));
686 
687  /*
688  * Walk over the remote tables and try to match them to locally known
689  * tables. If the table is not known locally create a new state for
690  * it.
691  *
692  * Also builds array of local oids of remote tables for the next step.
693  */
694  off = 0;
695  pubrel_local_oids = palloc(list_length(pubrel_names) * sizeof(Oid));
696 
697  foreach(lc, pubrel_names)
698  {
699  RangeVar *rv = (RangeVar *) lfirst(lc);
700  Oid relid;
701 
702  relid = RangeVarGetRelid(rv, AccessShareLock, false);
703 
704  /* Check for supported relkind. */
706  rv->schemaname, rv->relname);
707 
708  pubrel_local_oids[off++] = relid;
709 
710  if (!bsearch(&relid, subrel_local_oids,
711  list_length(subrel_states), sizeof(Oid), oid_cmp))
712  {
713  AddSubscriptionRelState(sub->oid, relid,
714  copy_data ? SUBREL_STATE_INIT : SUBREL_STATE_READY,
716  ereport(DEBUG1,
717  (errmsg_internal("table \"%s.%s\" added to subscription \"%s\"",
718  rv->schemaname, rv->relname, sub->name)));
719  }
720  }
721 
722  /*
723  * Next remove state for tables we should not care about anymore using
724  * the data we collected above
725  */
726  qsort(pubrel_local_oids, list_length(pubrel_names),
727  sizeof(Oid), oid_cmp);
728 
729  remove_rel_len = 0;
730  for (off = 0; off < list_length(subrel_states); off++)
731  {
732  Oid relid = subrel_local_oids[off];
733 
734  if (!bsearch(&relid, pubrel_local_oids,
735  list_length(pubrel_names), sizeof(Oid), oid_cmp))
736  {
737  char state;
738  XLogRecPtr statelsn;
739 
740  /*
741  * Lock pg_subscription_rel with AccessExclusiveLock to
742  * prevent any race conditions with the apply worker
743  * re-launching workers at the same time this code is trying
744  * to remove those tables.
745  *
746  * Even if new worker for this particular rel is restarted it
747  * won't be able to make any progress as we hold exclusive
748  * lock on subscription_rel till the transaction end. It will
749  * simply exit as there is no corresponding rel entry.
750  *
751  * This locking also ensures that the state of rels won't
752  * change till we are done with this refresh operation.
753  */
754  if (!rel)
755  rel = table_open(SubscriptionRelRelationId, AccessExclusiveLock);
756 
757  /* Last known rel state. */
758  state = GetSubscriptionRelState(sub->oid, relid, &statelsn);
759 
760  sub_remove_rels[remove_rel_len].relid = relid;
761  sub_remove_rels[remove_rel_len++].state = state;
762 
763  RemoveSubscriptionRel(sub->oid, relid);
764 
765  logicalrep_worker_stop(sub->oid, relid);
766 
767  /*
768  * For READY state, we would have already dropped the
769  * tablesync origin.
770  */
771  if (state != SUBREL_STATE_READY)
772  {
773  char originname[NAMEDATALEN];
774 
775  /*
776  * Drop the tablesync's origin tracking if exists.
777  *
778  * It is possible that the origin is not yet created for
779  * tablesync worker, this can happen for the states before
780  * SUBREL_STATE_FINISHEDCOPY. The apply worker can also
781  * concurrently try to drop the origin and by this time
782  * the origin might be already removed. For these reasons,
783  * passing missing_ok = true.
784  */
785  ReplicationOriginNameForTablesync(sub->oid, relid, originname,
786  sizeof(originname));
787  replorigin_drop_by_name(originname, true, false);
788  }
789 
790  ereport(DEBUG1,
791  (errmsg_internal("table \"%s.%s\" removed from subscription \"%s\"",
793  get_rel_name(relid),
794  sub->name)));
795  }
796  }
797 
798  /*
799  * Drop the tablesync slots associated with removed tables. This has
800  * to be at the end because otherwise if there is an error while doing
801  * the database operations we won't be able to rollback dropped slots.
802  */
803  for (off = 0; off < remove_rel_len; off++)
804  {
805  if (sub_remove_rels[off].state != SUBREL_STATE_READY &&
806  sub_remove_rels[off].state != SUBREL_STATE_SYNCDONE)
807  {
808  char syncslotname[NAMEDATALEN] = {0};
809 
810  /*
811  * For READY/SYNCDONE states we know the tablesync slot has
812  * already been dropped by the tablesync worker.
813  *
814  * For other states, there is no certainty, maybe the slot
815  * does not exist yet. Also, if we fail after removing some of
816  * the slots, next time, it will again try to drop already
817  * dropped slots and fail. For these reasons, we allow
818  * missing_ok = true for the drop.
819  */
820  ReplicationSlotNameForTablesync(sub->oid, sub_remove_rels[off].relid,
821  syncslotname, sizeof(syncslotname));
822  ReplicationSlotDropAtPubNode(wrconn, syncslotname, true);
823  }
824  }
825  }
826  PG_FINALLY();
827  {
828  walrcv_disconnect(wrconn);
829  }
830  PG_END_TRY();
831 
832  if (rel)
833  table_close(rel, NoLock);
834 }
static List * fetch_table_list(WalReceiverConn *wrconn, List *publications)
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
#define DEBUG1
Definition: elog.h:25
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
void RemoveSubscriptionRel(Oid subid, Oid relid)
void ReplicationSlotDropAtPubNode(WalReceiverConn *wrconn, char *slotname, bool missing_ok)
#define RangeVarGetRelid(relation, lockmode, missing_ok)
Definition: namespace.h:79
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1974
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1923
void replorigin_drop_by_name(const char *name, bool missing_ok, bool nowait)
Definition: origin.c:414
#define AccessShareLock
Definition: lockdefs.h:36
int errcode(int sqlerrcode)
Definition: elog.c:698
unsigned int Oid
Definition: postgres_ext.h:31
static WalReceiverConn * wrconn
Definition: walreceiver.c:94
char * schemaname
Definition: primnodes.h:67
#define NAMEDATALEN
char * relname
Definition: primnodes.h:68
#define ERROR
Definition: elog.h:46
void AddSubscriptionRelState(Oid subid, Oid relid, char state, XLogRecPtr sublsn)
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3316
#define NoLock
Definition: lockdefs.h:34
void logicalrep_worker_stop(Oid subid, Oid relid)
Definition: launcher.c:436
List * GetSubscriptionRelations(Oid subid)
void CheckSubscriptionRelkind(char relkind, const char *nspname, const char *relname)
#define PG_FINALLY()
Definition: elog.h:330
char GetSubscriptionRelState(Oid subid, Oid relid, XLogRecPtr *sublsn)
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define lfirst(lc)
Definition: pg_list.h:169
Definition: regguts.h:317
void load_file(const char *filename, bool restricted)
Definition: dfmgr.c:146
int oid_cmp(const void *p1, const void *p2)
Definition: oid.c:336
static int list_length(const List *l)
Definition: pg_list.h:149
void ReplicationOriginNameForTablesync(Oid suboid, Oid relid, char *originname, int szorgname)
Definition: tablesync.c:905
#define walrcv_disconnect(conn)
Definition: walreceiver.h:432
#define AccessExclusiveLock
Definition: lockdefs.h:45
void * palloc(Size size)
Definition: mcxt.c:1062
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define qsort(a, b, c, d)
Definition: port.h:504
#define PG_TRY()
Definition: elog.h:313
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Definition: pg_list.h:50
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1899
#define PG_END_TRY()
Definition: elog.h:338
void ReplicationSlotNameForTablesync(Oid suboid, Oid relid, char *syncslotname, int szslot)
Definition: tablesync.c:892
#define walrcv_connect(conninfo, logical, appname, err)
Definition: walreceiver.h:404

◆ AlterSubscriptionOwner()

ObjectAddress AlterSubscriptionOwner ( const char *  name,
Oid  newOwnerId 
)

Definition at line 1511 of file subscriptioncmds.c.

References AlterSubscriptionOwner_internal(), CStringGetDatum, ereport, errcode(), errmsg(), ERROR, GETSTRUCT, heap_freetuple(), HeapTupleIsValid, MyDatabaseId, ObjectAddressSet, RowExclusiveLock, SearchSysCacheCopy2, SUBSCRIPTIONNAME, table_close(), and table_open().

Referenced by ExecAlterOwnerStmt().

1512 {
1513  Oid subid;
1514  HeapTuple tup;
1515  Relation rel;
1516  ObjectAddress address;
1517  Form_pg_subscription form;
1518 
1519  rel = table_open(SubscriptionRelationId, RowExclusiveLock);
1520 
1523 
1524  if (!HeapTupleIsValid(tup))
1525  ereport(ERROR,
1526  (errcode(ERRCODE_UNDEFINED_OBJECT),
1527  errmsg("subscription \"%s\" does not exist", name)));
1528 
1529  form = (Form_pg_subscription) GETSTRUCT(tup);
1530  subid = form->oid;
1531 
1532  AlterSubscriptionOwner_internal(rel, tup, newOwnerId);
1533 
1534  ObjectAddressSet(address, SubscriptionRelationId, subid);
1535 
1536  heap_freetuple(tup);
1537 
1539 
1540  return address;
1541 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
int errcode(int sqlerrcode)
Definition: elog.c:698
FormData_pg_subscription * Form_pg_subscription
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
#define ERROR
Definition: elog.h:46
#define RowExclusiveLock
Definition: lockdefs.h:38
#define CStringGetDatum(X)
Definition: postgres.h:622
Oid MyDatabaseId
Definition: globals.c:88
#define ereport(elevel,...)
Definition: elog.h:157
static void AlterSubscriptionOwner_internal(Relation rel, HeapTuple tup, Oid newOwnerId)
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
const char * name
Definition: encode.c:515
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define SearchSysCacheCopy2(cacheId, key1, key2)
Definition: syscache.h:177
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39

◆ AlterSubscriptionOwner_internal()

static void AlterSubscriptionOwner_internal ( Relation  rel,
HeapTuple  tup,
Oid  newOwnerId 
)
static

Definition at line 1474 of file subscriptioncmds.c.

References aclcheck_error(), ACLCHECK_NOT_OWNER, CatalogTupleUpdate(), changeDependencyOnOwner(), ereport, errcode(), errhint(), errmsg(), ERROR, GETSTRUCT, GetUserId(), InvokeObjectPostAlterHook, NameStr, OBJECT_SUBSCRIPTION, pg_subscription_ownercheck(), superuser_arg(), and HeapTupleData::t_self.

Referenced by AlterSubscriptionOwner(), and AlterSubscriptionOwner_oid().

1475 {
1476  Form_pg_subscription form;
1477 
1478  form = (Form_pg_subscription) GETSTRUCT(tup);
1479 
1480  if (form->subowner == newOwnerId)
1481  return;
1482 
1483  if (!pg_subscription_ownercheck(form->oid, GetUserId()))
1485  NameStr(form->subname));
1486 
1487  /* New owner must be a superuser */
1488  if (!superuser_arg(newOwnerId))
1489  ereport(ERROR,
1490  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1491  errmsg("permission denied to change owner of subscription \"%s\"",
1492  NameStr(form->subname)),
1493  errhint("The owner of a subscription must be a superuser.")));
1494 
1495  form->subowner = newOwnerId;
1496  CatalogTupleUpdate(rel, &tup->t_self, tup);
1497 
1498  /* Update owner dependency reference */
1499  changeDependencyOnOwner(SubscriptionRelationId,
1500  form->oid,
1501  newOwnerId);
1502 
1503  InvokeObjectPostAlterHook(SubscriptionRelationId,
1504  form->oid, 0);
1505 }
int errhint(const char *fmt,...)
Definition: elog.c:1156
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
Oid GetUserId(void)
Definition: miscinit.c:478
int errcode(int sqlerrcode)
Definition: elog.c:698
FormData_pg_subscription * Form_pg_subscription
void changeDependencyOnOwner(Oid classId, Oid objectId, Oid newOwnerId)
Definition: pg_shdepend.c:311
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3308
#define ERROR
Definition: elog.h:46
ItemPointerData t_self
Definition: htup.h:65
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:175
bool superuser_arg(Oid roleid)
Definition: superuser.c:56
#define ereport(elevel,...)
Definition: elog.h:157
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define NameStr(name)
Definition: c.h:681
bool pg_subscription_ownercheck(Oid sub_oid, Oid roleid)
Definition: aclchk.c:5382

◆ AlterSubscriptionOwner_oid()

void AlterSubscriptionOwner_oid ( Oid  subid,
Oid  newOwnerId 
)

Definition at line 1547 of file subscriptioncmds.c.

References AlterSubscriptionOwner_internal(), ereport, errcode(), errmsg(), ERROR, heap_freetuple(), HeapTupleIsValid, ObjectIdGetDatum, RowExclusiveLock, SearchSysCacheCopy1, SUBSCRIPTIONOID, table_close(), and table_open().

Referenced by shdepReassignOwned().

1548 {
1549  HeapTuple tup;
1550  Relation rel;
1551 
1552  rel = table_open(SubscriptionRelationId, RowExclusiveLock);
1553 
1555 
1556  if (!HeapTupleIsValid(tup))
1557  ereport(ERROR,
1558  (errcode(ERRCODE_UNDEFINED_OBJECT),
1559  errmsg("subscription with OID %u does not exist", subid)));
1560 
1561  AlterSubscriptionOwner_internal(rel, tup, newOwnerId);
1562 
1563  heap_freetuple(tup);
1564 
1566 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
int errcode(int sqlerrcode)
Definition: elog.c:698
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
#define RowExclusiveLock
Definition: lockdefs.h:38
#define ereport(elevel,...)
Definition: elog.h:157
static void AlterSubscriptionOwner_internal(Relation rel, HeapTuple tup, Oid newOwnerId)
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:175
int errmsg(const char *fmt,...)
Definition: elog.c:909
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39

◆ check_duplicates_in_publist()

static void check_duplicates_in_publist ( List publist,
Datum datums 
)
static

Definition at line 1687 of file subscriptioncmds.c.

References CStringGetTextDatum, ereport, errcode(), ERRCODE_DUPLICATE_OBJECT, errmsg(), ERROR, lfirst, name, and strVal.

Referenced by merge_publications(), and publicationListToArray().

1688 {
1689  ListCell *cell;
1690  int j = 0;
1691 
1692  foreach(cell, publist)
1693  {
1694  char *name = strVal(lfirst(cell));
1695  ListCell *pcell;
1696 
1697  foreach(pcell, publist)
1698  {
1699  char *pname = strVal(lfirst(pcell));
1700 
1701  if (pcell == cell)
1702  break;
1703 
1704  if (strcmp(name, pname) == 0)
1705  ereport(ERROR,
1707  errmsg("publication name \"%s\" used more than once",
1708  pname)));
1709  }
1710 
1711  if (datums)
1712  datums[j++] = CStringGetTextDatum(name);
1713  }
1714 }
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:698
#define ERROR
Definition: elog.h:46
#define ereport(elevel,...)
Definition: elog.h:157
#define lfirst(lc)
Definition: pg_list.h:169
const char * name
Definition: encode.c:515
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define CStringGetTextDatum(s)
Definition: builtins.h:82
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:32

◆ CreateSubscription()

ObjectAddress CreateSubscription ( ParseState pstate,
CreateSubscriptionStmt stmt,
bool  isTopLevel 
)

Definition at line 394 of file subscriptioncmds.c.

References AccessShareLock, AddSubscriptionRelState(), ApplyLauncherWakeupAtCommit(), Assert, SubOpts::binary, BoolGetDatum, CatalogTupleInsert(), CharGetDatum, CheckSubscriptionRelkind(), SubOpts::connect, CreateSubscriptionStmt::conninfo, SubOpts::copy_data, SubOpts::create_slot, CRS_NOEXPORT_SNAPSHOT, CStringGetDatum, CStringGetTextDatum, DirectFunctionCall1, elog, SubOpts::enabled, ereport, errcode(), ERRCODE_DUPLICATE_OBJECT, errmsg(), ERROR, fetch_table_list(), get_rel_relkind(), GetNewOidWithIndex(), GetSysCacheOid2, GetUserId(), heap_form_tuple(), heap_freetuple(), InvalidXLogRecPtr, InvokeObjectPostCreateHook, IsSet, lfirst, load_file(), LOGICALREP_TWOPHASE_STATE_DISABLED, LOGICALREP_TWOPHASE_STATE_ENABLED, LOGICALREP_TWOPHASE_STATE_PENDING, MyDatabaseId, NAMEDATALEN, namein(), NIL, NOTICE, ObjectAddressSet, ObjectIdGetDatum, OidIsValid, CreateSubscriptionStmt::options, opts, parse_subscription_options(), PG_END_TRY, PG_FINALLY, PG_TRY, PreventInTransactionBlock(), CreateSubscriptionStmt::publication, publicationListToArray(), RangeVarGetRelid, recordDependencyOnOwner(), RelationGetDescr, RangeVar::relname, replorigin_create(), RowExclusiveLock, RangeVar::schemaname, SubOpts::slot_name, snprintf, SubOpts::specified_opts, SubOpts::streaming, CreateSubscriptionStmt::subname, SUBOPT_BINARY, SUBOPT_CONNECT, SUBOPT_COPY_DATA, SUBOPT_CREATE_SLOT, SUBOPT_ENABLED, SUBOPT_SLOT_NAME, SUBOPT_STREAMING, SUBOPT_SYNCHRONOUS_COMMIT, SUBOPT_TWOPHASE_COMMIT, SUBSCRIPTIONNAME, superuser(), SubOpts::synchronous_commit, table_close(), table_open(), SubOpts::twophase, UpdateTwoPhaseState(), values, walrcv_check_conninfo, walrcv_connect, walrcv_create_slot, walrcv_disconnect, WARNING, and wrconn.

Referenced by ProcessUtilitySlow().

396 {
397  Relation rel;
398  ObjectAddress myself;
399  Oid subid;
400  bool nulls[Natts_pg_subscription];
401  Datum values[Natts_pg_subscription];
402  Oid owner = GetUserId();
403  HeapTuple tup;
404  char *conninfo;
405  char originname[NAMEDATALEN];
406  List *publications;
407  bits32 supported_opts;
408  SubOpts opts = {0};
409 
410  /*
411  * Parse and check options.
412  *
413  * Connection and publication should not be specified here.
414  */
415  supported_opts = (SUBOPT_CONNECT | SUBOPT_ENABLED | SUBOPT_CREATE_SLOT |
419  parse_subscription_options(pstate, stmt->options, supported_opts, &opts);
420 
421  /*
422  * Since creating a replication slot is not transactional, rolling back
423  * the transaction leaves the created replication slot. So we cannot run
424  * CREATE SUBSCRIPTION inside a transaction block if creating a
425  * replication slot.
426  */
427  if (opts.create_slot)
428  PreventInTransactionBlock(isTopLevel, "CREATE SUBSCRIPTION ... WITH (create_slot = true)");
429 
430  if (!superuser())
431  ereport(ERROR,
432  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
433  errmsg("must be superuser to create subscriptions")));
434 
435  /*
436  * If built with appropriate switch, whine when regression-testing
437  * conventions for subscription names are violated.
438  */
439 #ifdef ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS
440  if (strncmp(stmt->subname, "regress_", 8) != 0)
441  elog(WARNING, "subscriptions created by regression test cases should have names starting with \"regress_\"");
442 #endif
443 
444  rel = table_open(SubscriptionRelationId, RowExclusiveLock);
445 
446  /* Check if name is used */
447  subid = GetSysCacheOid2(SUBSCRIPTIONNAME, Anum_pg_subscription_oid,
449  if (OidIsValid(subid))
450  {
451  ereport(ERROR,
453  errmsg("subscription \"%s\" already exists",
454  stmt->subname)));
455  }
456 
457  if (!IsSet(opts.specified_opts, SUBOPT_SLOT_NAME) &&
458  opts.slot_name == NULL)
459  opts.slot_name = stmt->subname;
460 
461  /* The default for synchronous_commit of subscriptions is off. */
462  if (opts.synchronous_commit == NULL)
463  opts.synchronous_commit = "off";
464 
465  conninfo = stmt->conninfo;
466  publications = stmt->publication;
467 
468  /* Load the library providing us libpq calls. */
469  load_file("libpqwalreceiver", false);
470 
471  /* Check the connection info string. */
472  walrcv_check_conninfo(conninfo);
473 
474  /* Everything ok, form a new tuple. */
475  memset(values, 0, sizeof(values));
476  memset(nulls, false, sizeof(nulls));
477 
478  subid = GetNewOidWithIndex(rel, SubscriptionObjectIndexId,
479  Anum_pg_subscription_oid);
480  values[Anum_pg_subscription_oid - 1] = ObjectIdGetDatum(subid);
481  values[Anum_pg_subscription_subdbid - 1] = ObjectIdGetDatum(MyDatabaseId);
482  values[Anum_pg_subscription_subname - 1] =
484  values[Anum_pg_subscription_subowner - 1] = ObjectIdGetDatum(owner);
485  values[Anum_pg_subscription_subenabled - 1] = BoolGetDatum(opts.enabled);
486  values[Anum_pg_subscription_subbinary - 1] = BoolGetDatum(opts.binary);
487  values[Anum_pg_subscription_substream - 1] = BoolGetDatum(opts.streaming);
488  values[Anum_pg_subscription_subtwophasestate - 1] =
489  CharGetDatum(opts.twophase ?
492  values[Anum_pg_subscription_subconninfo - 1] =
493  CStringGetTextDatum(conninfo);
494  if (opts.slot_name)
495  values[Anum_pg_subscription_subslotname - 1] =
497  else
498  nulls[Anum_pg_subscription_subslotname - 1] = true;
499  values[Anum_pg_subscription_subsynccommit - 1] =
501  values[Anum_pg_subscription_subpublications - 1] =
502  publicationListToArray(publications);
503 
504  tup = heap_form_tuple(RelationGetDescr(rel), values, nulls);
505 
506  /* Insert tuple into catalog. */
507  CatalogTupleInsert(rel, tup);
508  heap_freetuple(tup);
509 
510  recordDependencyOnOwner(SubscriptionRelationId, subid, owner);
511 
512  snprintf(originname, sizeof(originname), "pg_%u", subid);
513  replorigin_create(originname);
514 
515  /*
516  * Connect to remote side to execute requested commands and fetch table
517  * info.
518  */
519  if (opts.connect)
520  {
521  char *err;
523  List *tables;
524  ListCell *lc;
525  char table_state;
526 
527  /* Try to connect to the publisher. */
528  wrconn = walrcv_connect(conninfo, true, stmt->subname, &err);
529  if (!wrconn)
530  ereport(ERROR,
531  (errcode(ERRCODE_CONNECTION_FAILURE),
532  errmsg("could not connect to the publisher: %s", err)));
533 
534  PG_TRY();
535  {
536  /*
537  * Set sync state based on if we were asked to do data copy or
538  * not.
539  */
540  table_state = opts.copy_data ? SUBREL_STATE_INIT : SUBREL_STATE_READY;
541 
542  /*
543  * Get the table list from publisher and build local table status
544  * info.
545  */
546  tables = fetch_table_list(wrconn, publications);
547  foreach(lc, tables)
548  {
549  RangeVar *rv = (RangeVar *) lfirst(lc);
550  Oid relid;
551 
552  relid = RangeVarGetRelid(rv, AccessShareLock, false);
553 
554  /* Check for supported relkind. */
556  rv->schemaname, rv->relname);
557 
558  AddSubscriptionRelState(subid, relid, table_state,
560  }
561 
562  /*
563  * If requested, create permanent slot for the subscription. We
564  * won't use the initial snapshot for anything, so no need to
565  * export it.
566  */
567  if (opts.create_slot)
568  {
569  bool twophase_enabled = false;
570 
571  Assert(opts.slot_name);
572 
573  /*
574  * Even if two_phase is set, don't create the slot with
575  * two-phase enabled. Will enable it once all the tables are
576  * synced and ready. This avoids race-conditions like prepared
577  * transactions being skipped due to changes not being applied
578  * due to checks in should_apply_changes_for_rel() when
579  * tablesync for the corresponding tables are in progress. See
580  * comments atop worker.c.
581  *
582  * Note that if tables were specified but copy_data is false
583  * then it is safe to enable two_phase up-front because those
584  * tables are already initially in READY state. When the
585  * subscription has no tables, we leave the twophase state as
586  * PENDING, to allow ALTER SUBSCRIPTION ... REFRESH
587  * PUBLICATION to work.
588  */
589  if (opts.twophase && !opts.copy_data && tables != NIL)
590  twophase_enabled = true;
591 
592  walrcv_create_slot(wrconn, opts.slot_name, false, twophase_enabled,
593  CRS_NOEXPORT_SNAPSHOT, NULL);
594 
595  if (twophase_enabled)
597 
598  ereport(NOTICE,
599  (errmsg("created replication slot \"%s\" on publisher",
600  opts.slot_name)));
601  }
602  }
603  PG_FINALLY();
604  {
605  walrcv_disconnect(wrconn);
606  }
607  PG_END_TRY();
608  }
609  else
611  /* translator: %s is an SQL ALTER statement */
612  (errmsg("tables were not subscribed, you will have to run %s to subscribe the tables",
613  "ALTER SUBSCRIPTION ... REFRESH PUBLICATION")));
614 
616 
617  if (opts.enabled)
619 
620  ObjectAddressSet(myself, SubscriptionRelationId, subid);
621 
622  InvokeObjectPostCreateHook(SubscriptionRelationId, subid, 0);
623 
624  return myself;
625 }
#define NIL
Definition: pg_list.h:65
static List * fetch_table_list(WalReceiverConn *wrconn, List *publications)
Oid GetNewOidWithIndex(Relation relation, Oid indexId, AttrNumber oidcolumn)
Definition: catalog.c:381
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
Datum namein(PG_FUNCTION_ARGS)
Definition: name.c:48
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define InvokeObjectPostCreateHook(classId, objectId, subId)
Definition: objectaccess.h:151
bool copy_data
#define RelationGetDescr(relation)
Definition: rel.h:503
Oid GetUserId(void)
Definition: miscinit.c:478
#define LOGICALREP_TWOPHASE_STATE_DISABLED
#define RangeVarGetRelid(relation, lockmode, missing_ok)
Definition: namespace.h:79
#define walrcv_check_conninfo(conninfo)
Definition: walreceiver.h:406
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1974
bool create_slot
bits32 specified_opts
#define AccessShareLock
Definition: lockdefs.h:36
int errcode(int sqlerrcode)
Definition: elog.c:698
bool superuser(void)
Definition: superuser.c:46
#define SUBOPT_ENABLED
RepOriginId replorigin_create(const char *roname)
Definition: origin.c:240
static Datum publicationListToArray(List *publist)
#define SUBOPT_CREATE_SLOT
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:626
void recordDependencyOnOwner(Oid classId, Oid objectId, Oid owner)
Definition: pg_shdepend.c:163
#define SUBOPT_SYNCHRONOUS_COMMIT
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
static void parse_subscription_options(ParseState *pstate, List *stmt_options, bits32 supported_opts, SubOpts *opts)
#define SUBOPT_STREAMING
#define OidIsValid(objectId)
Definition: c.h:710
static WalReceiverConn * wrconn
Definition: walreceiver.c:94
char * schemaname
Definition: primnodes.h:67
#define LOGICALREP_TWOPHASE_STATE_ENABLED
#define NAMEDATALEN
char * relname
Definition: primnodes.h:68
#define SUBOPT_TWOPHASE_COMMIT
bool streaming
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
#define SUBOPT_CONNECT
#define SUBOPT_BINARY
void AddSubscriptionRelState(Oid subid, Oid relid, char state, XLogRecPtr sublsn)
#define RowExclusiveLock
Definition: lockdefs.h:38
#define LOGICALREP_TWOPHASE_STATE_PENDING
#define CStringGetDatum(X)
Definition: postgres.h:622
void PreventInTransactionBlock(bool isTopLevel, const char *stmtType)
Definition: xact.c:3379
char * slot_name
void CheckSubscriptionRelkind(char relkind, const char *nspname, const char *relname)
static AmcheckOptions opts
Definition: pg_amcheck.c:111
#define WARNING
Definition: elog.h:40
#define PG_FINALLY()
Definition: elog.h:330
uintptr_t Datum
Definition: postgres.h:411
void UpdateTwoPhaseState(Oid suboid, char new_state)
Definition: tablesync.c:1255
Oid MyDatabaseId
Definition: globals.c:88
#define BoolGetDatum(X)
Definition: postgres.h:446
#define ereport(elevel,...)
Definition: elog.h:157
#define NOTICE
Definition: elog.h:37
uint32 bits32
Definition: c.h:450
#define SUBOPT_COPY_DATA
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
#define GetSysCacheOid2(cacheId, oidcol, key1, key2)
Definition: syscache.h:195
void load_file(const char *filename, bool restricted)
Definition: dfmgr.c:146
#define walrcv_disconnect(conn)
Definition: walreceiver.h:432
#define SUBOPT_SLOT_NAME
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
#define CharGetDatum(X)
Definition: postgres.h:460
static Datum values[MAXATTR]
Definition: bootstrap.c:166
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define elog(elevel,...)
Definition: elog.h:232
#define CStringGetTextDatum(s)
Definition: builtins.h:82
void ApplyLauncherWakeupAtCommit(void)
Definition: launcher.c:780
#define PG_TRY()
Definition: elog.h:313
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:32
Definition: pg_list.h:50
#define snprintf
Definition: port.h:216
#define IsSet(val, bits)
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:221
#define PG_END_TRY()
Definition: elog.h:338
char * synchronous_commit
#define walrcv_create_slot(conn, slotname, temporary, two_phase, snapshot_action, lsn)
Definition: walreceiver.h:426
#define walrcv_connect(conninfo, logical, appname, err)
Definition: walreceiver.h:404

◆ DropSubscription()

void DropSubscription ( DropSubscriptionStmt stmt,
bool  isTopLevel 
)

Definition at line 1149 of file subscriptioncmds.c.

References AccessExclusiveLock, aclcheck_error(), ACLCHECK_NOT_OWNER, Assert, CatalogTupleDelete(), CStringGetDatum, DatumGetName, deleteSharedDependencyRecordsFor(), ereport, errcode(), errmsg(), ERROR, EventTriggerSQLDropAddObject(), GETSTRUCT, GetSubscriptionNotReadyRelations(), GetUserId(), HeapTupleIsValid, InvalidOid, InvokeObjectDropHook, lfirst, list_free(), load_file(), LockSharedObject(), logicalrep_worker_stop(), logicalrep_workers_find(), LW_SHARED, LWLockAcquire(), LWLockRelease(), DropSubscriptionStmt::missing_ok, MyDatabaseId, NAMEDATALEN, NameStr, NIL, NoLock, NOTICE, OBJECT_SUBSCRIPTION, ObjectAddressSet, OidIsValid, PG_END_TRY, PG_FINALLY, pg_subscription_ownercheck(), PG_TRY, PreventInTransactionBlock(), pstrdup(), ReleaseSysCache(), LogicalRepWorker::relid, SubscriptionRelState::relid, RemoveSubscriptionRel(), ReplicationOriginNameForTablesync(), ReplicationSlotDropAtPubNode(), ReplicationSlotNameForTablesync(), replorigin_drop_by_name(), ReportSlotConnectionError(), SearchSysCache2(), snprintf, SubscriptionRelState::state, LogicalRepWorker::subid, subname, DropSubscriptionStmt::subname, SUBSCRIPTIONNAME, SUBSCRIPTIONOID, SysCacheGetAttr(), HeapTupleData::t_self, table_close(), table_open(), TextDatumGetCString, walrcv_connect, walrcv_disconnect, and wrconn.

Referenced by ProcessUtilitySlow().

1150 {
1151  Relation rel;
1152  ObjectAddress myself;
1153  HeapTuple tup;
1154  Oid subid;
1155  Datum datum;
1156  bool isnull;
1157  char *subname;
1158  char *conninfo;
1159  char *slotname;
1160  List *subworkers;
1161  ListCell *lc;
1162  char originname[NAMEDATALEN];
1163  char *err = NULL;
1165  Form_pg_subscription form;
1166  List *rstates;
1167 
1168  /*
1169  * Lock pg_subscription with AccessExclusiveLock to ensure that the
1170  * launcher doesn't restart new worker during dropping the subscription
1171  */
1172  rel = table_open(SubscriptionRelationId, AccessExclusiveLock);
1173 
1175  CStringGetDatum(stmt->subname));
1176 
1177  if (!HeapTupleIsValid(tup))
1178  {
1179  table_close(rel, NoLock);
1180 
1181  if (!stmt->missing_ok)
1182  ereport(ERROR,
1183  (errcode(ERRCODE_UNDEFINED_OBJECT),
1184  errmsg("subscription \"%s\" does not exist",
1185  stmt->subname)));
1186  else
1187  ereport(NOTICE,
1188  (errmsg("subscription \"%s\" does not exist, skipping",
1189  stmt->subname)));
1190 
1191  return;
1192  }
1193 
1194  form = (Form_pg_subscription) GETSTRUCT(tup);
1195  subid = form->oid;
1196 
1197  /* must be owner */
1198  if (!pg_subscription_ownercheck(subid, GetUserId()))
1200  stmt->subname);
1201 
1202  /* DROP hook for the subscription being removed */
1203  InvokeObjectDropHook(SubscriptionRelationId, subid, 0);
1204 
1205  /*
1206  * Lock the subscription so nobody else can do anything with it (including
1207  * the replication workers).
1208  */
1209  LockSharedObject(SubscriptionRelationId, subid, 0, AccessExclusiveLock);
1210 
1211  /* Get subname */
1212  datum = SysCacheGetAttr(SUBSCRIPTIONOID, tup,
1213  Anum_pg_subscription_subname, &isnull);
1214  Assert(!isnull);
1215  subname = pstrdup(NameStr(*DatumGetName(datum)));
1216 
1217  /* Get conninfo */
1218  datum = SysCacheGetAttr(SUBSCRIPTIONOID, tup,
1219  Anum_pg_subscription_subconninfo, &isnull);
1220  Assert(!isnull);
1221  conninfo = TextDatumGetCString(datum);
1222 
1223  /* Get slotname */
1224  datum = SysCacheGetAttr(SUBSCRIPTIONOID, tup,
1225  Anum_pg_subscription_subslotname, &isnull);
1226  if (!isnull)
1227  slotname = pstrdup(NameStr(*DatumGetName(datum)));
1228  else
1229  slotname = NULL;
1230 
1231  /*
1232  * Since dropping a replication slot is not transactional, the replication
1233  * slot stays dropped even if the transaction rolls back. So we cannot
1234  * run DROP SUBSCRIPTION inside a transaction block if dropping the
1235  * replication slot.
1236  *
1237  * XXX The command name should really be something like "DROP SUBSCRIPTION
1238  * of a subscription that is associated with a replication slot", but we
1239  * don't have the proper facilities for that.
1240  */
1241  if (slotname)
1242  PreventInTransactionBlock(isTopLevel, "DROP SUBSCRIPTION");
1243 
1244  ObjectAddressSet(myself, SubscriptionRelationId, subid);
1245  EventTriggerSQLDropAddObject(&myself, true, true);
1246 
1247  /* Remove the tuple from catalog. */
1248  CatalogTupleDelete(rel, &tup->t_self);
1249 
1250  ReleaseSysCache(tup);
1251 
1252  /*
1253  * Stop all the subscription workers immediately.
1254  *
1255  * This is necessary if we are dropping the replication slot, so that the
1256  * slot becomes accessible.
1257  *
1258  * It is also necessary if the subscription is disabled and was disabled
1259  * in the same transaction. Then the workers haven't seen the disabling
1260  * yet and will still be running, leading to hangs later when we want to
1261  * drop the replication origin. If the subscription was disabled before
1262  * this transaction, then there shouldn't be any workers left, so this
1263  * won't make a difference.
1264  *
1265  * New workers won't be started because we hold an exclusive lock on the
1266  * subscription till the end of the transaction.
1267  */
1268  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
1269  subworkers = logicalrep_workers_find(subid, false);
1270  LWLockRelease(LogicalRepWorkerLock);
1271  foreach(lc, subworkers)
1272  {
1274 
1276  }
1277  list_free(subworkers);
1278 
1279  /*
1280  * Cleanup of tablesync replication origins.
1281  *
1282  * Any READY-state relations would already have dealt with clean-ups.
1283  *
1284  * Note that the state can't change because we have already stopped both
1285  * the apply and tablesync workers and they can't restart because of
1286  * exclusive lock on the subscription.
1287  */
1288  rstates = GetSubscriptionNotReadyRelations(subid);
1289  foreach(lc, rstates)
1290  {
1292  Oid relid = rstate->relid;
1293 
1294  /* Only cleanup resources of tablesync workers */
1295  if (!OidIsValid(relid))
1296  continue;
1297 
1298  /*
1299  * Drop the tablesync's origin tracking if exists.
1300  *
1301  * It is possible that the origin is not yet created for tablesync
1302  * worker so passing missing_ok = true. This can happen for the states
1303  * before SUBREL_STATE_FINISHEDCOPY.
1304  */
1305  ReplicationOriginNameForTablesync(subid, relid, originname,
1306  sizeof(originname));
1307  replorigin_drop_by_name(originname, true, false);
1308  }
1309 
1310  /* Clean up dependencies */
1311  deleteSharedDependencyRecordsFor(SubscriptionRelationId, subid, 0);
1312 
1313  /* Remove any associated relation synchronization states. */
1315 
1316  /* Remove the origin tracking if exists. */
1317  snprintf(originname, sizeof(originname), "pg_%u", subid);
1318  replorigin_drop_by_name(originname, true, false);
1319 
1320  /*
1321  * If there is no slot associated with the subscription, we can finish
1322  * here.
1323  */
1324  if (!slotname && rstates == NIL)
1325  {
1326  table_close(rel, NoLock);
1327  return;
1328  }
1329 
1330  /*
1331  * Try to acquire the connection necessary for dropping slots.
1332  *
1333  * Note: If the slotname is NONE/NULL then we allow the command to finish
1334  * and users need to manually cleanup the apply and tablesync worker slots
1335  * later.
1336  *
1337  * This has to be at the end because otherwise if there is an error while
1338  * doing the database operations we won't be able to rollback dropped
1339  * slot.
1340  */
1341  load_file("libpqwalreceiver", false);
1342 
1343  wrconn = walrcv_connect(conninfo, true, subname, &err);
1344  if (wrconn == NULL)
1345  {
1346  if (!slotname)
1347  {
1348  /* be tidy */
1349  list_free(rstates);
1350  table_close(rel, NoLock);
1351  return;
1352  }
1353  else
1354  {
1355  ReportSlotConnectionError(rstates, subid, slotname, err);
1356  }
1357  }
1358 
1359  PG_TRY();
1360  {
1361  foreach(lc, rstates)
1362  {
1364  Oid relid = rstate->relid;
1365 
1366  /* Only cleanup resources of tablesync workers */
1367  if (!OidIsValid(relid))
1368  continue;
1369 
1370  /*
1371  * Drop the tablesync slots associated with removed tables.
1372  *
1373  * For SYNCDONE/READY states, the tablesync slot is known to have
1374  * already been dropped by the tablesync worker.
1375  *
1376  * For other states, there is no certainty, maybe the slot does
1377  * not exist yet. Also, if we fail after removing some of the
1378  * slots, next time, it will again try to drop already dropped
1379  * slots and fail. For these reasons, we allow missing_ok = true
1380  * for the drop.
1381  */
1382  if (rstate->state != SUBREL_STATE_SYNCDONE)
1383  {
1384  char syncslotname[NAMEDATALEN] = {0};
1385 
1386  ReplicationSlotNameForTablesync(subid, relid, syncslotname,
1387  sizeof(syncslotname));
1388  ReplicationSlotDropAtPubNode(wrconn, syncslotname, true);
1389  }
1390  }
1391 
1392  list_free(rstates);
1393 
1394  /*
1395  * If there is a slot associated with the subscription, then drop the
1396  * replication slot at the publisher.
1397  */
1398  if (slotname)
1399  ReplicationSlotDropAtPubNode(wrconn, slotname, false);
1400 
1401  }
1402  PG_FINALLY();
1403  {
1404  walrcv_disconnect(wrconn);
1405  }
1406  PG_END_TRY();
1407 
1408  table_close(rel, NoLock);
1409 }
#define NIL
Definition: pg_list.h:65
List * logicalrep_workers_find(Oid subid, bool only_running)
Definition: launcher.c:243
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
void RemoveSubscriptionRel(Oid subid, Oid relid)
void ReplicationSlotDropAtPubNode(WalReceiverConn *wrconn, char *slotname, bool missing_ok)
Oid GetUserId(void)
Definition: miscinit.c:478
char * pstrdup(const char *in)
Definition: mcxt.c:1299
#define InvokeObjectDropHook(classId, objectId, subId)
Definition: objectaccess.h:160
void replorigin_drop_by_name(const char *name, bool missing_ok, bool nowait)
Definition: origin.c:414
static void ReportSlotConnectionError(List *rstates, Oid subid, char *slotname, char *err)
int errcode(int sqlerrcode)
Definition: elog.c:698
void CatalogTupleDelete(Relation heapRel, ItemPointer tid)
Definition: indexing.c:350
FormData_pg_subscription * Form_pg_subscription
unsigned int Oid
Definition: postgres_ext.h:31
NameData subname
#define OidIsValid(objectId)
Definition: c.h:710
static WalReceiverConn * wrconn
Definition: walreceiver.c:94
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
#define NAMEDATALEN
#define DatumGetName(X)
Definition: postgres.h:629
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3308
#define ERROR
Definition: elog.h:46
ItemPointerData t_self
Definition: htup.h:65
#define NoLock
Definition: lockdefs.h:34
void logicalrep_worker_stop(Oid subid, Oid relid)
Definition: launcher.c:436
#define CStringGetDatum(X)
Definition: postgres.h:622
void PreventInTransactionBlock(bool isTopLevel, const char *stmtType)
Definition: xact.c:3379
void deleteSharedDependencyRecordsFor(Oid classId, Oid objectId, int32 objectSubId)
Definition: pg_shdepend.c:997
#define PG_FINALLY()
Definition: elog.h:330
#define TextDatumGetCString(d)
Definition: builtins.h:83
uintptr_t Datum
Definition: postgres.h:411
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1388
Oid MyDatabaseId
Definition: globals.c:88
void LockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:1017
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:157
#define NOTICE
Definition: elog.h:37
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
void load_file(const char *filename, bool restricted)
Definition: dfmgr.c:146
void EventTriggerSQLDropAddObject(const ObjectAddress *object, bool original, bool normal)
HeapTuple SearchSysCache2(int cacheId, Datum key1, Datum key2)
Definition: syscache.c:1138
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1199
void ReplicationOriginNameForTablesync(Oid suboid, Oid relid, char *originname, int szorgname)
Definition: tablesync.c:905
#define walrcv_disconnect(conn)
Definition: walreceiver.h:432
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
#define AccessExclusiveLock
Definition: lockdefs.h:45
int errmsg(const char *fmt,...)
Definition: elog.c:909
void list_free(List *list)
Definition: list.c:1391
#define NameStr(name)
Definition: c.h:681
#define PG_TRY()
Definition: elog.h:313
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Definition: pg_list.h:50
List * GetSubscriptionNotReadyRelations(Oid subid)
#define snprintf
Definition: port.h:216
#define PG_END_TRY()
Definition: elog.h:338
void ReplicationSlotNameForTablesync(Oid suboid, Oid relid, char *syncslotname, int szslot)
Definition: tablesync.c:892
bool pg_subscription_ownercheck(Oid sub_oid, Oid roleid)
Definition: aclchk.c:5382
#define walrcv_connect(conninfo, logical, appname, err)
Definition: walreceiver.h:404

◆ fetch_table_list()

static List * fetch_table_list ( WalReceiverConn wrconn,
List publications 
)
static

Definition at line 1573 of file subscriptioncmds.c.

References appendStringInfoChar(), appendStringInfoString(), Assert, StringInfoData::data, ereport, WalRcvExecResult::err, errcode(), errmsg(), ERROR, ExecClearTuple(), ExecDropSingleTupleTableSlot(), initStringInfo(), lappend(), lfirst, list_length(), makeRangeVar(), MakeSingleTupleTableSlot(), NIL, pfree(), quote_literal_cstr(), relname, slot_getattr(), WalRcvExecResult::status, strVal, TextDatumGetCString, TTSOpsMinimalTuple, WalRcvExecResult::tupledesc, WalRcvExecResult::tuplestore, tuplestore_gettupleslot(), walrcv_clear_result(), walrcv_exec, and WALRCV_OK_TUPLES.

Referenced by AlterSubscription_refresh(), and CreateSubscription().

1574 {
1575  WalRcvExecResult *res;
1576  StringInfoData cmd;
1577  TupleTableSlot *slot;
1578  Oid tableRow[2] = {TEXTOID, TEXTOID};
1579  ListCell *lc;
1580  bool first;
1581  List *tablelist = NIL;
1582 
1583  Assert(list_length(publications) > 0);
1584 
1585  initStringInfo(&cmd);
1586  appendStringInfoString(&cmd, "SELECT DISTINCT t.schemaname, t.tablename\n"
1587  " FROM pg_catalog.pg_publication_tables t\n"
1588  " WHERE t.pubname IN (");
1589  first = true;
1590  foreach(lc, publications)
1591  {
1592  char *pubname = strVal(lfirst(lc));
1593 
1594  if (first)
1595  first = false;
1596  else
1597  appendStringInfoString(&cmd, ", ");
1598 
1600  }
1601  appendStringInfoChar(&cmd, ')');
1602 
1603  res = walrcv_exec(wrconn, cmd.data, 2, tableRow);
1604  pfree(cmd.data);
1605 
1606  if (res->status != WALRCV_OK_TUPLES)
1607  ereport(ERROR,
1608  (errcode(ERRCODE_CONNECTION_FAILURE),
1609  errmsg("could not receive list of replicated tables from the publisher: %s",
1610  res->err)));
1611 
1612  /* Process tables. */
1614  while (tuplestore_gettupleslot(res->tuplestore, true, false, slot))
1615  {
1616  char *nspname;
1617  char *relname;
1618  bool isnull;
1619  RangeVar *rv;
1620 
1621  nspname = TextDatumGetCString(slot_getattr(slot, 1, &isnull));
1622  Assert(!isnull);
1623  relname = TextDatumGetCString(slot_getattr(slot, 2, &isnull));
1624  Assert(!isnull);
1625 
1626  rv = makeRangeVar(nspname, relname, -1);
1627  tablelist = lappend(tablelist, rv);
1628 
1629  ExecClearTuple(slot);
1630  }
1632 
1633  walrcv_clear_result(res);
1634 
1635  return tablelist;
1636 }
#define NIL
Definition: pg_list.h:65
char * quote_literal_cstr(const char *rawstr)
Definition: quote.c:102
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:425
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1238
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:698
NameData relname
Definition: pg_class.h:38
unsigned int Oid
Definition: postgres_ext.h:31
static void walrcv_clear_result(WalRcvExecResult *walres)
Definition: walreceiver.h:436
void pfree(void *pointer)
Definition: mcxt.c:1169
TupleDesc tupledesc
Definition: walreceiver.h:220
#define ERROR
Definition: elog.h:46
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1254
List * lappend(List *list, void *datum)
Definition: list.c:336
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
#define TextDatumGetCString(d)
Definition: builtins.h:83
static Datum slot_getattr(TupleTableSlot *slot, int attnum, bool *isnull)
Definition: tuptable.h:381
#define ereport(elevel,...)
Definition: elog.h:157
bool tuplestore_gettupleslot(Tuplestorestate *state, bool forward, bool copy, TupleTableSlot *slot)
Definition: tuplestore.c:1078
Tuplestorestate * tuplestore
Definition: walreceiver.h:219
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
WalRcvExecStatus status
Definition: walreceiver.h:216
static int list_length(const List *l)
Definition: pg_list.h:149
int errmsg(const char *fmt,...)
Definition: elog.c:909
Definition: pg_list.h:50
const TupleTableSlotOps TTSOpsMinimalTuple
Definition: execTuples.c:85
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:422
#define walrcv_exec(conn, exec, nRetTypes, retTypes)
Definition: walreceiver.h:430

◆ merge_publications()

static List * merge_publications ( List oldpublist,
List newpublist,
bool  addpub,
const char *  subname 
)
static

Definition at line 1727 of file subscriptioncmds.c.

References check_duplicates_in_publist(), ereport, errcode(), ERRCODE_DUPLICATE_OBJECT, errmsg(), ERROR, foreach_delete_current, lappend(), lfirst, list_copy(), makeString(), name, and strVal.

Referenced by AlterSubscription().

1728 {
1729  ListCell *lc;
1730 
1731  oldpublist = list_copy(oldpublist);
1732 
1733  check_duplicates_in_publist(newpublist, NULL);
1734 
1735  foreach(lc, newpublist)
1736  {
1737  char *name = strVal(lfirst(lc));
1738  ListCell *lc2;
1739  bool found = false;
1740 
1741  foreach(lc2, oldpublist)
1742  {
1743  char *pubname = strVal(lfirst(lc2));
1744 
1745  if (strcmp(name, pubname) == 0)
1746  {
1747  found = true;
1748  if (addpub)
1749  ereport(ERROR,
1751  errmsg("publication \"%s\" is already in subscription \"%s\"",
1752  name, subname)));
1753  else
1754  oldpublist = foreach_delete_current(oldpublist, lc2);
1755 
1756  break;
1757  }
1758  }
1759 
1760  if (addpub && !found)
1761  oldpublist = lappend(oldpublist, makeString(name));
1762  else if (!addpub && !found)
1763  ereport(ERROR,
1764  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1765  errmsg("publication \"%s\" is not in subscription \"%s\"",
1766  name, subname)));
1767  }
1768 
1769  /*
1770  * XXX Probably no strong reason for this, but for now it's to make ALTER
1771  * SUBSCRIPTION ... DROP PUBLICATION consistent with SET PUBLICATION.
1772  */
1773  if (!oldpublist)
1774  ereport(ERROR,
1775  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1776  errmsg("cannot drop all the publications from a subscription")));
1777 
1778  return oldpublist;
1779 }
Value * makeString(char *str)
Definition: value.c:53
List * list_copy(const List *oldlist)
Definition: list.c:1418
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:698
NameData subname
#define foreach_delete_current(lst, cell)
Definition: pg_list.h:369
#define ERROR
Definition: elog.h:46
List * lappend(List *list, void *datum)
Definition: list.c:336
static void check_duplicates_in_publist(List *publist, Datum *datums)
#define ereport(elevel,...)
Definition: elog.h:157
#define lfirst(lc)
Definition: pg_list.h:169
const char * name
Definition: encode.c:515
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:32

◆ parse_subscription_options()

static void parse_subscription_options ( ParseState pstate,
List stmt_options,
bits32  supported_opts,
SubOpts opts 
)
static

Definition at line 101 of file subscriptioncmds.c.

References Assert, SubOpts::binary, SubOpts::connect, SubOpts::copy_data, SubOpts::create_slot, defGetBoolean(), defGetString(), DefElem::defname, SubOpts::enabled, ereport, errcode(), errmsg(), ERROR, errorConflictingDefElem(), GUC_ACTION_SET, IsSet, lfirst, PGC_BACKEND, PGC_S_TEST, SubOpts::refresh, ReplicationSlotValidateName(), set_config_option(), SubOpts::slot_name, SubOpts::specified_opts, SubOpts::streaming, SUBOPT_BINARY, SUBOPT_CONNECT, SUBOPT_COPY_DATA, SUBOPT_CREATE_SLOT, SUBOPT_ENABLED, SUBOPT_REFRESH, SUBOPT_SLOT_NAME, SUBOPT_STREAMING, SUBOPT_SYNCHRONOUS_COMMIT, SUBOPT_TWOPHASE_COMMIT, SubOpts::synchronous_commit, and SubOpts::twophase.

Referenced by AlterSubscription(), and CreateSubscription().

103 {
104  ListCell *lc;
105 
106  /* caller must expect some option */
107  Assert(supported_opts != 0);
108 
109  /* If connect option is supported, these others also need to be. */
110  Assert(!IsSet(supported_opts, SUBOPT_CONNECT) ||
111  IsSet(supported_opts, SUBOPT_ENABLED | SUBOPT_CREATE_SLOT |
113 
114  /* Set default values for the boolean supported options. */
115  if (IsSet(supported_opts, SUBOPT_CONNECT))
116  opts->connect = true;
117  if (IsSet(supported_opts, SUBOPT_ENABLED))
118  opts->enabled = true;
119  if (IsSet(supported_opts, SUBOPT_CREATE_SLOT))
120  opts->create_slot = true;
121  if (IsSet(supported_opts, SUBOPT_COPY_DATA))
122  opts->copy_data = true;
123  if (IsSet(supported_opts, SUBOPT_REFRESH))
124  opts->refresh = true;
125  if (IsSet(supported_opts, SUBOPT_BINARY))
126  opts->binary = false;
127  if (IsSet(supported_opts, SUBOPT_STREAMING))
128  opts->streaming = false;
129  if (IsSet(supported_opts, SUBOPT_TWOPHASE_COMMIT))
130  opts->twophase = false;
131 
132  /* Parse options */
133  foreach(lc, stmt_options)
134  {
135  DefElem *defel = (DefElem *) lfirst(lc);
136 
137  if (IsSet(supported_opts, SUBOPT_CONNECT) &&
138  strcmp(defel->defname, "connect") == 0)
139  {
140  if (IsSet(opts->specified_opts, SUBOPT_CONNECT))
141  errorConflictingDefElem(defel, pstate);
142 
144  opts->connect = defGetBoolean(defel);
145  }
146  else if (IsSet(supported_opts, SUBOPT_ENABLED) &&
147  strcmp(defel->defname, "enabled") == 0)
148  {
149  if (IsSet(opts->specified_opts, SUBOPT_ENABLED))
150  errorConflictingDefElem(defel, pstate);
151 
153  opts->enabled = defGetBoolean(defel);
154  }
155  else if (IsSet(supported_opts, SUBOPT_CREATE_SLOT) &&
156  strcmp(defel->defname, "create_slot") == 0)
157  {
159  errorConflictingDefElem(defel, pstate);
160 
162  opts->create_slot = defGetBoolean(defel);
163  }
164  else if (IsSet(supported_opts, SUBOPT_SLOT_NAME) &&
165  strcmp(defel->defname, "slot_name") == 0)
166  {
168  errorConflictingDefElem(defel, pstate);
169 
171  opts->slot_name = defGetString(defel);
172 
173  /* Setting slot_name = NONE is treated as no slot name. */
174  if (strcmp(opts->slot_name, "none") == 0)
175  opts->slot_name = NULL;
176  else
178  }
179  else if (IsSet(supported_opts, SUBOPT_COPY_DATA) &&
180  strcmp(defel->defname, "copy_data") == 0)
181  {
183  errorConflictingDefElem(defel, pstate);
184 
186  opts->copy_data = defGetBoolean(defel);
187  }
188  else if (IsSet(supported_opts, SUBOPT_SYNCHRONOUS_COMMIT) &&
189  strcmp(defel->defname, "synchronous_commit") == 0)
190  {
192  errorConflictingDefElem(defel, pstate);
193 
195  opts->synchronous_commit = defGetString(defel);
196 
197  /* Test if the given value is valid for synchronous_commit GUC. */
198  (void) set_config_option("synchronous_commit", opts->synchronous_commit,
200  false, 0, false);
201  }
202  else if (IsSet(supported_opts, SUBOPT_REFRESH) &&
203  strcmp(defel->defname, "refresh") == 0)
204  {
205  if (IsSet(opts->specified_opts, SUBOPT_REFRESH))
206  errorConflictingDefElem(defel, pstate);
207 
209  opts->refresh = defGetBoolean(defel);
210  }
211  else if (IsSet(supported_opts, SUBOPT_BINARY) &&
212  strcmp(defel->defname, "binary") == 0)
213  {
214  if (IsSet(opts->specified_opts, SUBOPT_BINARY))
215  errorConflictingDefElem(defel, pstate);
216 
217  opts->specified_opts |= SUBOPT_BINARY;
218  opts->binary = defGetBoolean(defel);
219  }
220  else if (IsSet(supported_opts, SUBOPT_STREAMING) &&
221  strcmp(defel->defname, "streaming") == 0)
222  {
224  errorConflictingDefElem(defel, pstate);
225 
227  opts->streaming = defGetBoolean(defel);
228  }
229  else if (strcmp(defel->defname, "two_phase") == 0)
230  {
231  /*
232  * Do not allow toggling of two_phase option. Doing so could cause
233  * missing of transactions and lead to an inconsistent replica.
234  * See comments atop worker.c
235  *
236  * Note: Unsupported twophase indicates that this call originated
237  * from AlterSubscription.
238  */
239  if (!IsSet(supported_opts, SUBOPT_TWOPHASE_COMMIT))
240  ereport(ERROR,
241  (errcode(ERRCODE_SYNTAX_ERROR),
242  errmsg("unrecognized subscription parameter: \"%s\"", defel->defname)));
243 
245  errorConflictingDefElem(defel, pstate);
246 
248  opts->twophase = defGetBoolean(defel);
249  }
250  else
251  ereport(ERROR,
252  (errcode(ERRCODE_SYNTAX_ERROR),
253  errmsg("unrecognized subscription parameter: \"%s\"", defel->defname)));
254  }
255 
256  /*
257  * We've been explicitly asked to not connect, that requires some
258  * additional processing.
259  */
260  if (!opts->connect && IsSet(supported_opts, SUBOPT_CONNECT))
261  {
262  /* Check for incompatible options from the user. */
263  if (opts->enabled &&
264  IsSet(supported_opts, SUBOPT_ENABLED) &&
266  ereport(ERROR,
267  (errcode(ERRCODE_SYNTAX_ERROR),
268  /*- translator: both %s are strings of the form "option = value" */
269  errmsg("%s and %s are mutually exclusive options",
270  "connect = false", "enabled = true")));
271 
272  if (opts->create_slot &&
273  IsSet(supported_opts, SUBOPT_CREATE_SLOT) &&
275  ereport(ERROR,
276  (errcode(ERRCODE_SYNTAX_ERROR),
277  errmsg("%s and %s are mutually exclusive options",
278  "connect = false", "create_slot = true")));
279 
280  if (opts->copy_data &&
281  IsSet(supported_opts, SUBOPT_COPY_DATA) &&
283  ereport(ERROR,
284  (errcode(ERRCODE_SYNTAX_ERROR),
285  errmsg("%s and %s are mutually exclusive options",
286  "connect = false", "copy_data = true")));
287 
288  /* Change the defaults of other options. */
289  opts->enabled = false;
290  opts->create_slot = false;
291  opts->copy_data = false;
292  }
293 
294  /*
295  * Do additional checking for disallowed combination when slot_name = NONE
296  * was used.
297  */
298  if (!opts->slot_name &&
299  IsSet(supported_opts, SUBOPT_SLOT_NAME) &&
301  {
302  if (opts->enabled &&
303  IsSet(supported_opts, SUBOPT_ENABLED) &&
305  ereport(ERROR,
306  (errcode(ERRCODE_SYNTAX_ERROR),
307  /*- translator: both %s are strings of the form "option = value" */
308  errmsg("%s and %s are mutually exclusive options",
309  "slot_name = NONE", "enabled = true")));
310 
311  if (opts->create_slot &&
312  IsSet(supported_opts, SUBOPT_CREATE_SLOT) &&
314  ereport(ERROR,
315  (errcode(ERRCODE_SYNTAX_ERROR),
316  /*- translator: both %s are strings of the form "option = value" */
317  errmsg("%s and %s are mutually exclusive options",
318  "slot_name = NONE", "create_slot = true")));
319 
320  if (opts->enabled &&
321  IsSet(supported_opts, SUBOPT_ENABLED) &&
323  ereport(ERROR,
324  (errcode(ERRCODE_SYNTAX_ERROR),
325  /*- translator: both %s are strings of the form "option = value" */
326  errmsg("subscription with %s must also set %s",
327  "slot_name = NONE", "enabled = false")));
328 
329  if (opts->create_slot &&
330  IsSet(supported_opts, SUBOPT_CREATE_SLOT) &&
332  ereport(ERROR,
333  (errcode(ERRCODE_SYNTAX_ERROR),
334  /*- translator: both %s are strings of the form "option = value" */
335  errmsg("subscription with %s must also set %s",
336  "slot_name = NONE", "create_slot = false")));
337  }
338 
339  /*
340  * Do additional checking for the disallowed combination of two_phase and
341  * streaming. While streaming and two_phase can theoretically be
342  * supported, it needs more analysis to allow them together.
343  */
344  if (opts->twophase &&
345  IsSet(supported_opts, SUBOPT_TWOPHASE_COMMIT) &&
347  {
348  if (opts->streaming &&
349  IsSet(supported_opts, SUBOPT_STREAMING) &&
351  ereport(ERROR,
352  (errcode(ERRCODE_SYNTAX_ERROR),
353  /*- translator: both %s are strings of the form "option = value" */
354  errmsg("%s and %s are mutually exclusive options",
355  "two_phase = true", "streaming = true")));
356  }
357 }
bool copy_data
bool create_slot
bits32 specified_opts
int errcode(int sqlerrcode)
Definition: elog.c:698
#define SUBOPT_ENABLED
#define SUBOPT_CREATE_SLOT
#define SUBOPT_SYNCHRONOUS_COMMIT
#define SUBOPT_STREAMING
bool ReplicationSlotValidateName(const char *name, int elevel)
Definition: slot.c:172
bool defGetBoolean(DefElem *def)
Definition: define.c:111
#define SUBOPT_TWOPHASE_COMMIT
bool streaming
#define ERROR
Definition: elog.h:46
#define SUBOPT_CONNECT
char * defGetString(DefElem *def)
Definition: define.c:49
#define SUBOPT_BINARY
#define SUBOPT_REFRESH
char * slot_name
#define ereport(elevel,...)
Definition: elog.h:157
void errorConflictingDefElem(DefElem *defel, ParseState *pstate)
Definition: define.c:355
#define SUBOPT_COPY_DATA
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
#define SUBOPT_SLOT_NAME
int errmsg(const char *fmt,...)
Definition: elog.c:909
char * defname
Definition: parsenodes.h:746
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:7295
#define IsSet(val, bits)
char * synchronous_commit

◆ publicationListToArray()

static Datum publicationListToArray ( List publist)
static

Definition at line 363 of file subscriptioncmds.c.

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, check_duplicates_in_publist(), construct_array(), CurrentMemoryContext, list_length(), MemoryContextDelete(), MemoryContextSwitchTo(), palloc(), and PointerGetDatum.

Referenced by AlterSubscription(), and CreateSubscription().

364 {
365  ArrayType *arr;
366  Datum *datums;
367  MemoryContext memcxt;
368  MemoryContext oldcxt;
369 
370  /* Create memory context for temporary allocations. */
372  "publicationListToArray to array",
374  oldcxt = MemoryContextSwitchTo(memcxt);
375 
376  datums = (Datum *) palloc(sizeof(Datum) * list_length(publist));
377 
378  check_duplicates_in_publist(publist, datums);
379 
380  MemoryContextSwitchTo(oldcxt);
381 
382  arr = construct_array(datums, list_length(publist),
383  TEXTOID, -1, false, TYPALIGN_INT);
384 
385  MemoryContextDelete(memcxt);
386 
387  return PointerGetDatum(arr);
388 }
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:218
#define AllocSetContextCreate
Definition: memutils.h:173
#define PointerGetDatum(X)
Definition: postgres.h:600
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
ArrayType * construct_array(Datum *elems, int nelems, Oid elmtype, int elmlen, bool elmbyval, char elmalign)
Definition: arrayfuncs.c:3318
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:195
MemoryContext CurrentMemoryContext
Definition: mcxt.c:42
static void check_duplicates_in_publist(List *publist, Datum *datums)
uintptr_t Datum
Definition: postgres.h:411
static int list_length(const List *l)
Definition: pg_list.h:149
void * palloc(Size size)
Definition: mcxt.c:1062

◆ ReplicationSlotDropAtPubNode()

void ReplicationSlotDropAtPubNode ( WalReceiverConn wrconn,
char *  slotname,
bool  missing_ok 
)

Definition at line 1419 of file subscriptioncmds.c.

References appendStringInfo(), Assert, StringInfoData::data, ereport, WalRcvExecResult::err, errcode(), errmsg(), ERROR, initStringInfo(), load_file(), LOG, NOTICE, pfree(), PG_END_TRY, PG_FINALLY, PG_TRY, quote_identifier(), WalRcvExecResult::sqlstate, WalRcvExecResult::status, walrcv_clear_result(), WALRCV_ERROR, walrcv_exec, and WALRCV_OK_COMMAND.

Referenced by AlterSubscription_refresh(), DropSubscription(), LogicalRepSyncTableStart(), and process_syncing_tables_for_sync().

1420 {
1421  StringInfoData cmd;
1422 
1423  Assert(wrconn);
1424 
1425  load_file("libpqwalreceiver", false);
1426 
1427  initStringInfo(&cmd);
1428  appendStringInfo(&cmd, "DROP_REPLICATION_SLOT %s WAIT", quote_identifier(slotname));
1429 
1430  PG_TRY();
1431  {
1432  WalRcvExecResult *res;
1433 
1434  res = walrcv_exec(wrconn, cmd.data, 0, NULL);
1435 
1436  if (res->status == WALRCV_OK_COMMAND)
1437  {
1438  /* NOTICE. Success. */
1439  ereport(NOTICE,
1440  (errmsg("dropped replication slot \"%s\" on publisher",
1441  slotname)));
1442  }
1443  else if (res->status == WALRCV_ERROR &&
1444  missing_ok &&
1445  res->sqlstate == ERRCODE_UNDEFINED_OBJECT)
1446  {
1447  /* LOG. Error, but missing_ok = true. */
1448  ereport(LOG,
1449  (errmsg("could not drop replication slot \"%s\" on publisher: %s",
1450  slotname, res->err)));
1451  }
1452  else
1453  {
1454  /* ERROR. */
1455  ereport(ERROR,
1456  (errcode(ERRCODE_CONNECTION_FAILURE),
1457  errmsg("could not drop replication slot \"%s\" on publisher: %s",
1458  slotname, res->err)));
1459  }
1460 
1461  walrcv_clear_result(res);
1462  }
1463  PG_FINALLY();
1464  {
1465  pfree(cmd.data);
1466  }
1467  PG_END_TRY();
1468 }
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:11332
int errcode(int sqlerrcode)
Definition: elog.c:698
#define LOG
Definition: elog.h:26
static void walrcv_clear_result(WalRcvExecResult *walres)
Definition: walreceiver.h:436
void pfree(void *pointer)
Definition: mcxt.c:1169
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
#define ERROR
Definition: elog.h:46
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
#define PG_FINALLY()
Definition: elog.h:330
#define ereport(elevel,...)
Definition: elog.h:157
#define NOTICE
Definition: elog.h:37
#define Assert(condition)
Definition: c.h:804
WalRcvExecStatus status
Definition: walreceiver.h:216
void load_file(const char *filename, bool restricted)
Definition: dfmgr.c:146
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define PG_TRY()
Definition: elog.h:313
#define PG_END_TRY()
Definition: elog.h:338
#define walrcv_exec(conn, exec, nRetTypes, retTypes)
Definition: walreceiver.h:430

◆ ReportSlotConnectionError()

static void ReportSlotConnectionError ( List rstates,
Oid  subid,
char *  slotname,
char *  err 
)
static

Definition at line 1644 of file subscriptioncmds.c.

References elog, ereport, errcode(), errhint(), errmsg(), ERROR, lfirst, NAMEDATALEN, OidIsValid, SubscriptionRelState::relid, ReplicationSlotNameForTablesync(), SubscriptionRelState::state, and WARNING.

Referenced by DropSubscription().

1645 {
1646  ListCell *lc;
1647 
1648  foreach(lc, rstates)
1649  {
1651  Oid relid = rstate->relid;
1652 
1653  /* Only cleanup resources of tablesync workers */
1654  if (!OidIsValid(relid))
1655  continue;
1656 
1657  /*
1658  * Caller needs to ensure that relstate doesn't change underneath us.
1659  * See DropSubscription where we get the relstates.
1660  */
1661  if (rstate->state != SUBREL_STATE_SYNCDONE)
1662  {
1663  char syncslotname[NAMEDATALEN] = {0};
1664 
1665  ReplicationSlotNameForTablesync(subid, relid, syncslotname,
1666  sizeof(syncslotname));
1667  elog(WARNING, "could not drop tablesync replication slot \"%s\"",
1668  syncslotname);
1669  }
1670  }
1671 
1672  ereport(ERROR,
1673  (errcode(ERRCODE_CONNECTION_FAILURE),
1674  errmsg("could not connect to publisher when attempting to "
1675  "drop replication slot \"%s\": %s", slotname, err),
1676  /* translator: %s is an SQL ALTER command */
1677  errhint("Use %s to disassociate the subscription from the slot.",
1678  "ALTER SUBSCRIPTION ... SET (slot_name = NONE)")));
1679 }
int errhint(const char *fmt,...)
Definition: elog.c:1156
int errcode(int sqlerrcode)
Definition: elog.c:698
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:710
#define NAMEDATALEN
#define ERROR
Definition: elog.h:46
#define WARNING
Definition: elog.h:40
#define ereport(elevel,...)
Definition: elog.h:157
#define lfirst(lc)
Definition: pg_list.h:169
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define elog(elevel,...)
Definition: elog.h:232
void ReplicationSlotNameForTablesync(Oid suboid, Oid relid, char *syncslotname, int szslot)
Definition: tablesync.c:892