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 SUBOPT_DISABLE_ON_ERR   0x00000400
 
#define SUBOPT_LSN   0x00000800
 
#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 void get_publications_str (List *publications, StringInfo dest, bool quote_literal)
 
static void check_publications (WalReceiverConn *wrconn, List *publications)
 
static Datum publicationListToArray (List *publist)
 
ObjectAddress CreateSubscription (ParseState *pstate, CreateSubscriptionStmt *stmt, bool isTopLevel)
 
static void AlterSubscription_refresh (Subscription *sub, bool copy_data, List *validate_publications)
 
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))

Definition at line 69 of file subscriptioncmds.c.

◆ SUBOPT_BINARY

#define SUBOPT_BINARY   0x00000080

Definition at line 62 of file subscriptioncmds.c.

◆ SUBOPT_CONNECT

#define SUBOPT_CONNECT   0x00000001

Definition at line 55 of file subscriptioncmds.c.

◆ SUBOPT_COPY_DATA

#define SUBOPT_COPY_DATA   0x00000010

Definition at line 59 of file subscriptioncmds.c.

◆ SUBOPT_CREATE_SLOT

#define SUBOPT_CREATE_SLOT   0x00000004

Definition at line 57 of file subscriptioncmds.c.

◆ SUBOPT_DISABLE_ON_ERR

#define SUBOPT_DISABLE_ON_ERR   0x00000400

Definition at line 65 of file subscriptioncmds.c.

◆ SUBOPT_ENABLED

#define SUBOPT_ENABLED   0x00000002

Definition at line 56 of file subscriptioncmds.c.

◆ SUBOPT_LSN

#define SUBOPT_LSN   0x00000800

Definition at line 66 of file subscriptioncmds.c.

◆ SUBOPT_REFRESH

#define SUBOPT_REFRESH   0x00000040

Definition at line 61 of file subscriptioncmds.c.

◆ SUBOPT_SLOT_NAME

#define SUBOPT_SLOT_NAME   0x00000008

Definition at line 58 of file subscriptioncmds.c.

◆ SUBOPT_STREAMING

#define SUBOPT_STREAMING   0x00000100

Definition at line 63 of file subscriptioncmds.c.

◆ SUBOPT_SYNCHRONOUS_COMMIT

#define SUBOPT_SYNCHRONOUS_COMMIT   0x00000020

Definition at line 60 of file subscriptioncmds.c.

◆ SUBOPT_TWOPHASE_COMMIT

#define SUBOPT_TWOPHASE_COMMIT   0x00000200

Definition at line 64 of file subscriptioncmds.c.

Typedef Documentation

◆ SubOpts

typedef struct SubOpts SubOpts

Function Documentation

◆ AlterSubscription()

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

Definition at line 966 of file subscriptioncmds.c.

968 {
969  Relation rel;
970  ObjectAddress myself;
971  bool nulls[Natts_pg_subscription];
972  bool replaces[Natts_pg_subscription];
973  Datum values[Natts_pg_subscription];
974  HeapTuple tup;
975  Oid subid;
976  bool update_tuple = false;
977  Subscription *sub;
979  bits32 supported_opts;
980  SubOpts opts = {0};
981 
982  rel = table_open(SubscriptionRelationId, RowExclusiveLock);
983 
984  /* Fetch the existing tuple. */
986  CStringGetDatum(stmt->subname));
987 
988  if (!HeapTupleIsValid(tup))
989  ereport(ERROR,
990  (errcode(ERRCODE_UNDEFINED_OBJECT),
991  errmsg("subscription \"%s\" does not exist",
992  stmt->subname)));
993 
994  form = (Form_pg_subscription) GETSTRUCT(tup);
995  subid = form->oid;
996 
997  /* must be owner */
998  if (!pg_subscription_ownercheck(subid, GetUserId()))
1000  stmt->subname);
1001 
1002  sub = GetSubscription(subid, false);
1003 
1004  /* Lock the subscription so nobody else can do anything with it. */
1005  LockSharedObject(SubscriptionRelationId, subid, 0, AccessExclusiveLock);
1006 
1007  /* Form a new tuple. */
1008  memset(values, 0, sizeof(values));
1009  memset(nulls, false, sizeof(nulls));
1010  memset(replaces, false, sizeof(replaces));
1011 
1012  switch (stmt->kind)
1013  {
1015  {
1016  supported_opts = (SUBOPT_SLOT_NAME |
1019 
1020  parse_subscription_options(pstate, stmt->options,
1021  supported_opts, &opts);
1022 
1023  if (IsSet(opts.specified_opts, SUBOPT_SLOT_NAME))
1024  {
1025  /*
1026  * The subscription must be disabled to allow slot_name as
1027  * 'none', otherwise, the apply worker will repeatedly try
1028  * to stream the data using that slot_name which neither
1029  * exists on the publisher nor the user will be allowed to
1030  * create it.
1031  */
1032  if (sub->enabled && !opts.slot_name)
1033  ereport(ERROR,
1034  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1035  errmsg("cannot set %s for enabled subscription",
1036  "slot_name = NONE")));
1037 
1038  if (opts.slot_name)
1039  values[Anum_pg_subscription_subslotname - 1] =
1041  else
1042  nulls[Anum_pg_subscription_subslotname - 1] = true;
1043  replaces[Anum_pg_subscription_subslotname - 1] = true;
1044  }
1045 
1046  if (opts.synchronous_commit)
1047  {
1048  values[Anum_pg_subscription_subsynccommit - 1] =
1049  CStringGetTextDatum(opts.synchronous_commit);
1050  replaces[Anum_pg_subscription_subsynccommit - 1] = true;
1051  }
1052 
1053  if (IsSet(opts.specified_opts, SUBOPT_BINARY))
1054  {
1055  values[Anum_pg_subscription_subbinary - 1] =
1056  BoolGetDatum(opts.binary);
1057  replaces[Anum_pg_subscription_subbinary - 1] = true;
1058  }
1059 
1060  if (IsSet(opts.specified_opts, SUBOPT_STREAMING))
1061  {
1062  values[Anum_pg_subscription_substream - 1] =
1063  BoolGetDatum(opts.streaming);
1064  replaces[Anum_pg_subscription_substream - 1] = true;
1065  }
1066 
1067  if (IsSet(opts.specified_opts, SUBOPT_DISABLE_ON_ERR))
1068  {
1069  values[Anum_pg_subscription_subdisableonerr - 1]
1070  = BoolGetDatum(opts.disableonerr);
1071  replaces[Anum_pg_subscription_subdisableonerr - 1]
1072  = true;
1073  }
1074 
1075  update_tuple = true;
1076  break;
1077  }
1078 
1080  {
1081  parse_subscription_options(pstate, stmt->options,
1082  SUBOPT_ENABLED, &opts);
1083  Assert(IsSet(opts.specified_opts, SUBOPT_ENABLED));
1084 
1085  if (!sub->slotname && opts.enabled)
1086  ereport(ERROR,
1087  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1088  errmsg("cannot enable subscription that does not have a slot name")));
1089 
1090  values[Anum_pg_subscription_subenabled - 1] =
1091  BoolGetDatum(opts.enabled);
1092  replaces[Anum_pg_subscription_subenabled - 1] = true;
1093 
1094  if (opts.enabled)
1096 
1097  update_tuple = true;
1098  break;
1099  }
1100 
1102  /* Load the library providing us libpq calls. */
1103  load_file("libpqwalreceiver", false);
1104  /* Check the connection info string. */
1106 
1107  values[Anum_pg_subscription_subconninfo - 1] =
1109  replaces[Anum_pg_subscription_subconninfo - 1] = true;
1110  update_tuple = true;
1111  break;
1112 
1114  {
1115  supported_opts = SUBOPT_COPY_DATA | SUBOPT_REFRESH;
1116  parse_subscription_options(pstate, stmt->options,
1117  supported_opts, &opts);
1118 
1119  values[Anum_pg_subscription_subpublications - 1] =
1121  replaces[Anum_pg_subscription_subpublications - 1] = true;
1122 
1123  update_tuple = true;
1124 
1125  /* Refresh if user asked us to. */
1126  if (opts.refresh)
1127  {
1128  if (!sub->enabled)
1129  ereport(ERROR,
1130  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1131  errmsg("ALTER SUBSCRIPTION with refresh is not allowed for disabled subscriptions"),
1132  errhint("Use ALTER SUBSCRIPTION ... SET PUBLICATION ... WITH (refresh = false).")));
1133 
1134  /*
1135  * See ALTER_SUBSCRIPTION_REFRESH for details why this is
1136  * not allowed.
1137  */
1138  if (sub->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED && opts.copy_data)
1139  ereport(ERROR,
1140  (errcode(ERRCODE_SYNTAX_ERROR),
1141  errmsg("ALTER SUBSCRIPTION with refresh and copy_data is not allowed when two_phase is enabled"),
1142  errhint("Use ALTER SUBSCRIPTION ...SET PUBLICATION with refresh = false, or with copy_data = false"
1143  ", or use DROP/CREATE SUBSCRIPTION.")));
1144 
1145  PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION with refresh");
1146 
1147  /* Make sure refresh sees the new list of publications. */
1148  sub->publications = stmt->publication;
1149 
1150  AlterSubscription_refresh(sub, opts.copy_data,
1151  stmt->publication);
1152  }
1153 
1154  break;
1155  }
1156 
1159  {
1160  List *publist;
1161  bool isadd = stmt->kind == ALTER_SUBSCRIPTION_ADD_PUBLICATION;
1162 
1163  supported_opts = SUBOPT_REFRESH | SUBOPT_COPY_DATA;
1164  parse_subscription_options(pstate, stmt->options,
1165  supported_opts, &opts);
1166 
1167  publist = merge_publications(sub->publications, stmt->publication, isadd, stmt->subname);
1168  values[Anum_pg_subscription_subpublications - 1] =
1169  publicationListToArray(publist);
1170  replaces[Anum_pg_subscription_subpublications - 1] = true;
1171 
1172  update_tuple = true;
1173 
1174  /* Refresh if user asked us to. */
1175  if (opts.refresh)
1176  {
1177  /* We only need to validate user specified publications. */
1178  List *validate_publications = (isadd) ? stmt->publication : NULL;
1179 
1180  if (!sub->enabled)
1181  ereport(ERROR,
1182  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1183  errmsg("ALTER SUBSCRIPTION with refresh is not allowed for disabled subscriptions"),
1184  errhint("Use ALTER SUBSCRIPTION ... SET PUBLICATION ... WITH (refresh = false).")));
1185 
1186  /*
1187  * See ALTER_SUBSCRIPTION_REFRESH for details why this is
1188  * not allowed.
1189  */
1190  if (sub->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED && opts.copy_data)
1191  ereport(ERROR,
1192  (errcode(ERRCODE_SYNTAX_ERROR),
1193  errmsg("ALTER SUBSCRIPTION with refresh and copy_data is not allowed when two_phase is enabled"),
1194  errhint("Use ALTER SUBSCRIPTION ...SET PUBLICATION with refresh = false, or with copy_data = false"
1195  ", or use DROP/CREATE SUBSCRIPTION.")));
1196 
1197  PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION with refresh");
1198 
1199  /* Refresh the new list of publications. */
1200  sub->publications = publist;
1201 
1202  AlterSubscription_refresh(sub, opts.copy_data,
1203  validate_publications);
1204  }
1205 
1206  break;
1207  }
1208 
1210  {
1211  if (!sub->enabled)
1212  ereport(ERROR,
1213  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1214  errmsg("ALTER SUBSCRIPTION ... REFRESH is not allowed for disabled subscriptions")));
1215 
1216  parse_subscription_options(pstate, stmt->options,
1218 
1219  /*
1220  * The subscription option "two_phase" requires that
1221  * replication has passed the initial table synchronization
1222  * phase before the two_phase becomes properly enabled.
1223  *
1224  * But, having reached this two-phase commit "enabled" state
1225  * we must not allow any subsequent table initialization to
1226  * occur. So the ALTER SUBSCRIPTION ... REFRESH is disallowed
1227  * when the user had requested two_phase = on mode.
1228  *
1229  * The exception to this restriction is when copy_data =
1230  * false, because when copy_data is false the tablesync will
1231  * start already in READY state and will exit directly without
1232  * doing anything.
1233  *
1234  * For more details see comments atop worker.c.
1235  */
1236  if (sub->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED && opts.copy_data)
1237  ereport(ERROR,
1238  (errcode(ERRCODE_SYNTAX_ERROR),
1239  errmsg("ALTER SUBSCRIPTION ... REFRESH with copy_data is not allowed when two_phase is enabled"),
1240  errhint("Use ALTER SUBSCRIPTION ... REFRESH with copy_data = false"
1241  ", or use DROP/CREATE SUBSCRIPTION.")));
1242 
1243  PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION ... REFRESH");
1244 
1245  AlterSubscription_refresh(sub, opts.copy_data, NULL);
1246 
1247  break;
1248  }
1249 
1251  {
1253 
1254  /* ALTER SUBSCRIPTION ... SKIP supports only LSN option */
1255  Assert(IsSet(opts.specified_opts, SUBOPT_LSN));
1256 
1257  if (!superuser())
1258  ereport(ERROR,
1259  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1260  errmsg("must be superuser to skip transaction")));
1261 
1262  /*
1263  * If the user sets subskiplsn, we do a sanity check to make
1264  * sure that the specified LSN is a probable value.
1265  */
1266  if (!XLogRecPtrIsInvalid(opts.lsn))
1267  {
1268  RepOriginId originid;
1269  char originname[NAMEDATALEN];
1270  XLogRecPtr remote_lsn;
1271 
1272  snprintf(originname, sizeof(originname), "pg_%u", subid);
1273  originid = replorigin_by_name(originname, false);
1274  remote_lsn = replorigin_get_progress(originid, false);
1275 
1276  /* Check the given LSN is at least a future LSN */
1277  if (!XLogRecPtrIsInvalid(remote_lsn) && opts.lsn < remote_lsn)
1278  ereport(ERROR,
1279  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1280  errmsg("skip WAL location (LSN %X/%X) must be greater than origin LSN %X/%X",
1281  LSN_FORMAT_ARGS(opts.lsn),
1282  LSN_FORMAT_ARGS(remote_lsn))));
1283  }
1284 
1285  values[Anum_pg_subscription_subskiplsn - 1] = LSNGetDatum(opts.lsn);
1286  replaces[Anum_pg_subscription_subskiplsn - 1] = true;
1287 
1288  update_tuple = true;
1289  break;
1290  }
1291 
1292  default:
1293  elog(ERROR, "unrecognized ALTER SUBSCRIPTION kind %d",
1294  stmt->kind);
1295  }
1296 
1297  /* Update the catalog if needed. */
1298  if (update_tuple)
1299  {
1300  tup = heap_modify_tuple(tup, RelationGetDescr(rel), values, nulls,
1301  replaces);
1302 
1303  CatalogTupleUpdate(rel, &tup->t_self, tup);
1304 
1305  heap_freetuple(tup);
1306  }
1307 
1309 
1310  ObjectAddressSet(myself, SubscriptionRelationId, subid);
1311 
1312  InvokeObjectPostAlterHook(SubscriptionRelationId, subid, 0);
1313 
1314  return myself;
1315 }
@ ACLCHECK_NOT_OWNER
Definition: acl.h:184
bool pg_subscription_ownercheck(Oid sub_oid, Oid roleid)
Definition: aclchk.c:5735
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3512
static Datum values[MAXATTR]
Definition: bootstrap.c:156
#define CStringGetTextDatum(s)
Definition: builtins.h:85
uint32 bits32
Definition: c.h:450
void load_file(const char *filename, bool restricted)
Definition: dfmgr.c:144
int errhint(const char *fmt,...)
Definition: elog.c:1151
int errcode(int sqlerrcode)
Definition: elog.c:693
int errmsg(const char *fmt,...)
Definition: elog.c:904
#define ERROR
Definition: elog.h:33
#define elog(elevel,...)
Definition: elog.h:218
#define ereport(elevel,...)
Definition: elog.h:143
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:631
Oid MyDatabaseId
Definition: globals.c:89
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:1113
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:649
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
void ApplyLauncherWakeupAtCommit(void)
Definition: launcher.c:784
Assert(fmt[strlen(fmt) - 1] !='\n')
void LockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:1046
#define AccessExclusiveLock
Definition: lockdefs.h:43
#define RowExclusiveLock
Definition: lockdefs.h:38
Oid GetUserId(void)
Definition: miscinit.c:492
Datum namein(PG_FUNCTION_ARGS)
Definition: name.c:48
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:195
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
RepOriginId replorigin_by_name(const char *roname, bool missing_ok)
Definition: origin.c:209
XLogRecPtr replorigin_get_progress(RepOriginId node, bool flush)
Definition: origin.c:998
@ ALTER_SUBSCRIPTION_ENABLED
Definition: parsenodes.h:4075
@ ALTER_SUBSCRIPTION_DROP_PUBLICATION
Definition: parsenodes.h:4073
@ ALTER_SUBSCRIPTION_SET_PUBLICATION
Definition: parsenodes.h:4071
@ ALTER_SUBSCRIPTION_REFRESH
Definition: parsenodes.h:4074
@ ALTER_SUBSCRIPTION_SKIP
Definition: parsenodes.h:4076
@ ALTER_SUBSCRIPTION_OPTIONS
Definition: parsenodes.h:4069
@ ALTER_SUBSCRIPTION_CONNECTION
Definition: parsenodes.h:4070
@ ALTER_SUBSCRIPTION_ADD_PUBLICATION
Definition: parsenodes.h:4072
@ OBJECT_SUBSCRIPTION
Definition: parsenodes.h:2172
static AmcheckOptions opts
Definition: pg_amcheck.c:110
#define NAMEDATALEN
#define LSNGetDatum(X)
Definition: pg_lsn.h:22
Subscription * GetSubscription(Oid subid, bool missing_ok)
#define LOGICALREP_TWOPHASE_STATE_ENABLED
FormData_pg_subscription * Form_pg_subscription
#define snprintf
Definition: port.h:225
#define CStringGetDatum(X)
Definition: postgres.h:622
uintptr_t Datum
Definition: postgres.h:411
#define BoolGetDatum(X)
Definition: postgres.h:446
unsigned int Oid
Definition: postgres_ext.h:31
#define RelationGetDescr(relation)
Definition: rel.h:515
AlterSubscriptionType kind
Definition: parsenodes.h:4082
ItemPointerData t_self
Definition: htup.h:65
Definition: pg_list.h:51
#define SUBOPT_STREAMING
#define SUBOPT_SYNCHRONOUS_COMMIT
#define SUBOPT_ENABLED
static Datum publicationListToArray(List *publist)
static void parse_subscription_options(ParseState *pstate, List *stmt_options, bits32 supported_opts, SubOpts *opts)
#define SUBOPT_SLOT_NAME
#define SUBOPT_COPY_DATA
static void AlterSubscription_refresh(Subscription *sub, bool copy_data, List *validate_publications)
#define SUBOPT_DISABLE_ON_ERR
#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
bool superuser(void)
Definition: superuser.c:46
#define SearchSysCacheCopy2(cacheId, key1, key2)
Definition: syscache.h:181
@ SUBSCRIPTIONNAME
Definition: syscache.h:98
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define walrcv_check_conninfo(conninfo)
Definition: walreceiver.h:406
void PreventInTransactionBlock(bool isTopLevel, const char *stmtType)
Definition: xact.c:3462
#define LSN_FORMAT_ARGS(lsn)
Definition: xlogdefs.h:43
#define XLogRecPtrIsInvalid(r)
Definition: xlogdefs.h:29
uint16 RepOriginId
Definition: xlogdefs.h:65
uint64 XLogRecPtr
Definition: xlogdefs.h:21

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, ALTER_SUBSCRIPTION_SKIP, AlterSubscription_refresh(), ApplyLauncherWakeupAtCommit(), Assert(), BoolGetDatum, CatalogTupleUpdate(), AlterSubscriptionStmt::conninfo, CStringGetDatum, CStringGetTextDatum, DirectFunctionCall1, elog, Subscription::enabled, ereport, errcode(), errhint(), errmsg(), ERROR, GETSTRUCT, GetSubscription(), GetUserId(), heap_freetuple(), heap_modify_tuple(), HeapTupleIsValid, if(), InvokeObjectPostAlterHook, IsSet, AlterSubscriptionStmt::kind, load_file(), LockSharedObject(), LOGICALREP_TWOPHASE_STATE_ENABLED, LSN_FORMAT_ARGS, LSNGetDatum, merge_publications(), MyDatabaseId, NAMEDATALEN, namein(), OBJECT_SUBSCRIPTION, ObjectAddressSet, AlterSubscriptionStmt::options, opts, parse_subscription_options(), pg_subscription_ownercheck(), PreventInTransactionBlock(), AlterSubscriptionStmt::publication, publicationListToArray(), Subscription::publications, RelationGetDescr, replorigin_by_name(), replorigin_get_progress(), RowExclusiveLock, SearchSysCacheCopy2, Subscription::slotname, snprintf, AlterSubscriptionStmt::subname, SUBOPT_BINARY, SUBOPT_COPY_DATA, SUBOPT_DISABLE_ON_ERR, SUBOPT_ENABLED, SUBOPT_LSN, SUBOPT_REFRESH, SUBOPT_SLOT_NAME, SUBOPT_STREAMING, SUBOPT_SYNCHRONOUS_COMMIT, SUBSCRIPTIONNAME, superuser(), HeapTupleData::t_self, table_close(), table_open(), Subscription::twophasestate, values, walrcv_check_conninfo, and XLogRecPtrIsInvalid.

Referenced by ProcessUtilitySlow().

◆ AlterSubscription_refresh()

static void AlterSubscription_refresh ( Subscription sub,
bool  copy_data,
List validate_publications 
)
static

Definition at line 750 of file subscriptioncmds.c.

752 {
753  char *err;
754  List *pubrel_names;
755  List *subrel_states;
756  Oid *subrel_local_oids;
757  Oid *pubrel_local_oids;
758  ListCell *lc;
759  int off;
760  int remove_rel_len;
761  Relation rel = NULL;
762  typedef struct SubRemoveRels
763  {
764  Oid relid;
765  char state;
766  } SubRemoveRels;
767  SubRemoveRels *sub_remove_rels;
769 
770  /* Load the library providing us libpq calls. */
771  load_file("libpqwalreceiver", false);
772 
773  /* Try to connect to the publisher. */
774  wrconn = walrcv_connect(sub->conninfo, true, sub->name, &err);
775  if (!wrconn)
776  ereport(ERROR,
777  (errcode(ERRCODE_CONNECTION_FAILURE),
778  errmsg("could not connect to the publisher: %s", err)));
779 
780  PG_TRY();
781  {
782  if (validate_publications)
783  check_publications(wrconn, validate_publications);
784 
785  /* Get the table list from publisher. */
786  pubrel_names = fetch_table_list(wrconn, sub->publications);
787 
788  /* Get local table list. */
789  subrel_states = GetSubscriptionRelations(sub->oid);
790 
791  /*
792  * Build qsorted array of local table oids for faster lookup. This can
793  * potentially contain all tables in the database so speed of lookup
794  * is important.
795  */
796  subrel_local_oids = palloc(list_length(subrel_states) * sizeof(Oid));
797  off = 0;
798  foreach(lc, subrel_states)
799  {
801 
802  subrel_local_oids[off++] = relstate->relid;
803  }
804  qsort(subrel_local_oids, list_length(subrel_states),
805  sizeof(Oid), oid_cmp);
806 
807  /*
808  * Rels that we want to remove from subscription and drop any slots
809  * and origins corresponding to them.
810  */
811  sub_remove_rels = palloc(list_length(subrel_states) * sizeof(SubRemoveRels));
812 
813  /*
814  * Walk over the remote tables and try to match them to locally known
815  * tables. If the table is not known locally create a new state for
816  * it.
817  *
818  * Also builds array of local oids of remote tables for the next step.
819  */
820  off = 0;
821  pubrel_local_oids = palloc(list_length(pubrel_names) * sizeof(Oid));
822 
823  foreach(lc, pubrel_names)
824  {
825  RangeVar *rv = (RangeVar *) lfirst(lc);
826  Oid relid;
827 
828  relid = RangeVarGetRelid(rv, AccessShareLock, false);
829 
830  /* Check for supported relkind. */
832  rv->schemaname, rv->relname);
833 
834  pubrel_local_oids[off++] = relid;
835 
836  if (!bsearch(&relid, subrel_local_oids,
837  list_length(subrel_states), sizeof(Oid), oid_cmp))
838  {
839  AddSubscriptionRelState(sub->oid, relid,
840  copy_data ? SUBREL_STATE_INIT : SUBREL_STATE_READY,
842  ereport(DEBUG1,
843  (errmsg_internal("table \"%s.%s\" added to subscription \"%s\"",
844  rv->schemaname, rv->relname, sub->name)));
845  }
846  }
847 
848  /*
849  * Next remove state for tables we should not care about anymore using
850  * the data we collected above
851  */
852  qsort(pubrel_local_oids, list_length(pubrel_names),
853  sizeof(Oid), oid_cmp);
854 
855  remove_rel_len = 0;
856  for (off = 0; off < list_length(subrel_states); off++)
857  {
858  Oid relid = subrel_local_oids[off];
859 
860  if (!bsearch(&relid, pubrel_local_oids,
861  list_length(pubrel_names), sizeof(Oid), oid_cmp))
862  {
863  char state;
864  XLogRecPtr statelsn;
865 
866  /*
867  * Lock pg_subscription_rel with AccessExclusiveLock to
868  * prevent any race conditions with the apply worker
869  * re-launching workers at the same time this code is trying
870  * to remove those tables.
871  *
872  * Even if new worker for this particular rel is restarted it
873  * won't be able to make any progress as we hold exclusive
874  * lock on subscription_rel till the transaction end. It will
875  * simply exit as there is no corresponding rel entry.
876  *
877  * This locking also ensures that the state of rels won't
878  * change till we are done with this refresh operation.
879  */
880  if (!rel)
881  rel = table_open(SubscriptionRelRelationId, AccessExclusiveLock);
882 
883  /* Last known rel state. */
884  state = GetSubscriptionRelState(sub->oid, relid, &statelsn);
885 
886  sub_remove_rels[remove_rel_len].relid = relid;
887  sub_remove_rels[remove_rel_len++].state = state;
888 
889  RemoveSubscriptionRel(sub->oid, relid);
890 
891  logicalrep_worker_stop(sub->oid, relid);
892 
893  /*
894  * For READY state, we would have already dropped the
895  * tablesync origin.
896  */
897  if (state != SUBREL_STATE_READY)
898  {
899  char originname[NAMEDATALEN];
900 
901  /*
902  * Drop the tablesync's origin tracking if exists.
903  *
904  * It is possible that the origin is not yet created for
905  * tablesync worker, this can happen for the states before
906  * SUBREL_STATE_FINISHEDCOPY. The apply worker can also
907  * concurrently try to drop the origin and by this time
908  * the origin might be already removed. For these reasons,
909  * passing missing_ok = true.
910  */
911  ReplicationOriginNameForTablesync(sub->oid, relid, originname,
912  sizeof(originname));
913  replorigin_drop_by_name(originname, true, false);
914  }
915 
916  ereport(DEBUG1,
917  (errmsg_internal("table \"%s.%s\" removed from subscription \"%s\"",
919  get_rel_name(relid),
920  sub->name)));
921  }
922  }
923 
924  /*
925  * Drop the tablesync slots associated with removed tables. This has
926  * to be at the end because otherwise if there is an error while doing
927  * the database operations we won't be able to rollback dropped slots.
928  */
929  for (off = 0; off < remove_rel_len; off++)
930  {
931  if (sub_remove_rels[off].state != SUBREL_STATE_READY &&
932  sub_remove_rels[off].state != SUBREL_STATE_SYNCDONE)
933  {
934  char syncslotname[NAMEDATALEN] = {0};
935 
936  /*
937  * For READY/SYNCDONE states we know the tablesync slot has
938  * already been dropped by the tablesync worker.
939  *
940  * For other states, there is no certainty, maybe the slot
941  * does not exist yet. Also, if we fail after removing some of
942  * the slots, next time, it will again try to drop already
943  * dropped slots and fail. For these reasons, we allow
944  * missing_ok = true for the drop.
945  */
946  ReplicationSlotNameForTablesync(sub->oid, sub_remove_rels[off].relid,
947  syncslotname, sizeof(syncslotname));
948  ReplicationSlotDropAtPubNode(wrconn, syncslotname, true);
949  }
950  }
951  }
952  PG_FINALLY();
953  {
955  }
956  PG_END_TRY();
957 
958  if (rel)
959  table_close(rel, NoLock);
960 }
int errmsg_internal(const char *fmt,...)
Definition: elog.c:991
#define PG_END_TRY()
Definition: elog.h:324
#define PG_TRY()
Definition: elog.h:299
#define DEBUG1
Definition: elog.h:24
#define PG_FINALLY()
Definition: elog.h:316
void CheckSubscriptionRelkind(char relkind, const char *nspname, const char *relname)
void logicalrep_worker_stop(Oid subid, Oid relid)
Definition: launcher.c:436
#define NoLock
Definition: lockdefs.h:34
#define AccessShareLock
Definition: lockdefs.h:36
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3326
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1984
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1933
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1909
void * palloc(Size size)
Definition: mcxt.c:1068
#define RangeVarGetRelid(relation, lockmode, missing_ok)
Definition: namespace.h:79
int oid_cmp(const void *p1, const void *p2)
Definition: oid.c:336
void replorigin_drop_by_name(const char *name, bool missing_ok, bool nowait)
Definition: origin.c:414
#define lfirst(lc)
Definition: pg_list.h:169
static int list_length(const List *l)
Definition: pg_list.h:149
List * GetSubscriptionRelations(Oid subid)
void RemoveSubscriptionRel(Oid subid, Oid relid)
char GetSubscriptionRelState(Oid subid, Oid relid, XLogRecPtr *sublsn)
void AddSubscriptionRelState(Oid subid, Oid relid, char state, XLogRecPtr sublsn)
#define qsort(a, b, c, d)
Definition: port.h:495
char * relname
Definition: primnodes.h:68
char * schemaname
Definition: primnodes.h:67
Definition: regguts.h:318
static void check_publications(WalReceiverConn *wrconn, List *publications)
void ReplicationSlotDropAtPubNode(WalReceiverConn *wrconn, char *slotname, bool missing_ok)
static List * fetch_table_list(WalReceiverConn *wrconn, List *publications)
void ReplicationOriginNameForTablesync(Oid suboid, Oid relid, char *originname, int szorgname)
Definition: tablesync.c:1164
void ReplicationSlotNameForTablesync(Oid suboid, Oid relid, char *syncslotname, int szslot)
Definition: tablesync.c:1151
static WalReceiverConn * wrconn
Definition: walreceiver.c:95
#define walrcv_connect(conninfo, logical, appname, err)
Definition: walreceiver.h:404
#define walrcv_disconnect(conn)
Definition: walreceiver.h:432
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28

References AccessExclusiveLock, AccessShareLock, AddSubscriptionRelState(), check_publications(), 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().

◆ AlterSubscriptionOwner()

ObjectAddress AlterSubscriptionOwner ( const char *  name,
Oid  newOwnerId 
)

Definition at line 1697 of file subscriptioncmds.c.

1698 {
1699  Oid subid;
1700  HeapTuple tup;
1701  Relation rel;
1702  ObjectAddress address;
1703  Form_pg_subscription form;
1704 
1705  rel = table_open(SubscriptionRelationId, RowExclusiveLock);
1706 
1709 
1710  if (!HeapTupleIsValid(tup))
1711  ereport(ERROR,
1712  (errcode(ERRCODE_UNDEFINED_OBJECT),
1713  errmsg("subscription \"%s\" does not exist", name)));
1714 
1715  form = (Form_pg_subscription) GETSTRUCT(tup);
1716  subid = form->oid;
1717 
1718  AlterSubscriptionOwner_internal(rel, tup, newOwnerId);
1719 
1720  ObjectAddressSet(address, SubscriptionRelationId, subid);
1721 
1722  heap_freetuple(tup);
1723 
1725 
1726  return address;
1727 }
const char * name
Definition: encode.c:561
static void AlterSubscriptionOwner_internal(Relation rel, HeapTuple tup, Oid newOwnerId)

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

Referenced by ExecAlterOwnerStmt().

◆ AlterSubscriptionOwner_internal()

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

Definition at line 1658 of file subscriptioncmds.c.

1659 {
1660  Form_pg_subscription form;
1661 
1662  form = (Form_pg_subscription) GETSTRUCT(tup);
1663 
1664  if (form->subowner == newOwnerId)
1665  return;
1666 
1667  if (!pg_subscription_ownercheck(form->oid, GetUserId()))
1669  NameStr(form->subname));
1670 
1671  /* New owner must be a superuser */
1672  if (!superuser_arg(newOwnerId))
1673  ereport(ERROR,
1674  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1675  errmsg("permission denied to change owner of subscription \"%s\"",
1676  NameStr(form->subname)),
1677  errhint("The owner of a subscription must be a superuser.")));
1678 
1679  form->subowner = newOwnerId;
1680  CatalogTupleUpdate(rel, &tup->t_self, tup);
1681 
1682  /* Update owner dependency reference */
1683  changeDependencyOnOwner(SubscriptionRelationId,
1684  form->oid,
1685  newOwnerId);
1686 
1687  InvokeObjectPostAlterHook(SubscriptionRelationId,
1688  form->oid, 0);
1689 
1691 }
#define NameStr(name)
Definition: c.h:681
void changeDependencyOnOwner(Oid classId, Oid objectId, Oid newOwnerId)
Definition: pg_shdepend.c:312
bool superuser_arg(Oid roleid)
Definition: superuser.c:56

References aclcheck_error(), ACLCHECK_NOT_OWNER, ApplyLauncherWakeupAtCommit(), 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().

◆ AlterSubscriptionOwner_oid()

void AlterSubscriptionOwner_oid ( Oid  subid,
Oid  newOwnerId 
)

Definition at line 1733 of file subscriptioncmds.c.

1734 {
1735  HeapTuple tup;
1736  Relation rel;
1737 
1738  rel = table_open(SubscriptionRelationId, RowExclusiveLock);
1739 
1741 
1742  if (!HeapTupleIsValid(tup))
1743  ereport(ERROR,
1744  (errcode(ERRCODE_UNDEFINED_OBJECT),
1745  errmsg("subscription with OID %u does not exist", subid)));
1746 
1747  AlterSubscriptionOwner_internal(rel, tup, newOwnerId);
1748 
1749  heap_freetuple(tup);
1750 
1752 }
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:179
@ SUBSCRIPTIONOID
Definition: syscache.h:99

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

Referenced by shdepReassignOwned().

◆ check_duplicates_in_publist()

static void check_duplicates_in_publist ( List publist,
Datum datums 
)
static

Definition at line 1858 of file subscriptioncmds.c.

1859 {
1860  ListCell *cell;
1861  int j = 0;
1862 
1863  foreach(cell, publist)
1864  {
1865  char *name = strVal(lfirst(cell));
1866  ListCell *pcell;
1867 
1868  foreach(pcell, publist)
1869  {
1870  char *pname = strVal(lfirst(pcell));
1871 
1872  if (pcell == cell)
1873  break;
1874 
1875  if (strcmp(name, pname) == 0)
1876  ereport(ERROR,
1878  errmsg("publication name \"%s\" used more than once",
1879  pname)));
1880  }
1881 
1882  if (datums)
1883  datums[j++] = CStringGetTextDatum(name);
1884  }
1885 }
int j
Definition: isn.c:74
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:32
#define strVal(v)
Definition: value.h:72

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

Referenced by merge_publications(), and publicationListToArray().

◆ check_publications()

static void check_publications ( WalReceiverConn wrconn,
List publications 
)
static

Definition at line 412 of file subscriptioncmds.c.

413 {
415  StringInfo cmd;
416  TupleTableSlot *slot;
417  List *publicationsCopy = NIL;
418  Oid tableRow[1] = {TEXTOID};
419 
420  cmd = makeStringInfo();
421  appendStringInfoString(cmd, "SELECT t.pubname FROM\n"
422  " pg_catalog.pg_publication t WHERE\n"
423  " t.pubname IN (");
424  get_publications_str(publications, cmd, true);
425  appendStringInfoChar(cmd, ')');
426 
427  res = walrcv_exec(wrconn, cmd->data, 1, tableRow);
428  pfree(cmd->data);
429  pfree(cmd);
430 
431  if (res->status != WALRCV_OK_TUPLES)
432  ereport(ERROR,
433  errmsg_plural("could not receive publication from the publisher: %s",
434  "could not receive list of publications from the publisher: %s",
435  list_length(publications),
436  res->err));
437 
438  publicationsCopy = list_copy(publications);
439 
440  /* Process publication(s). */
441  slot = MakeSingleTupleTableSlot(res->tupledesc, &TTSOpsMinimalTuple);
442  while (tuplestore_gettupleslot(res->tuplestore, true, false, slot))
443  {
444  char *pubname;
445  bool isnull;
446 
447  pubname = TextDatumGetCString(slot_getattr(slot, 1, &isnull));
448  Assert(!isnull);
449 
450  /* Delete the publication present in publisher from the list. */
451  publicationsCopy = list_delete(publicationsCopy, makeString(pubname));
452  ExecClearTuple(slot);
453  }
454 
456 
458 
459  if (list_length(publicationsCopy))
460  {
461  /* Prepare the list of non-existent publication(s) for error message. */
462  StringInfo pubnames = makeStringInfo();
463 
464  get_publications_str(publicationsCopy, pubnames, false);
466  errcode(ERRCODE_UNDEFINED_OBJECT),
467  errmsg_plural("publication %s does not exist in the publisher",
468  "publications %s do not exist in the publisher",
469  list_length(publicationsCopy),
470  pubnames->data));
471  }
472 }
#define TextDatumGetCString(d)
Definition: builtins.h:86
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:1014
#define WARNING
Definition: elog.h:30
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1254
const TupleTableSlotOps TTSOpsMinimalTuple
Definition: execTuples.c:85
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1238
List * list_copy(const List *oldlist)
Definition: list.c:1532
List * list_delete(List *list, void *datum)
Definition: list.c:812
void pfree(void *pointer)
Definition: mcxt.c:1175
#define NIL
Definition: pg_list.h:65
StringInfo makeStringInfo(void)
Definition: stringinfo.c:41
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
static void get_publications_str(List *publications, StringInfo dest, bool quote_literal)
bool tuplestore_gettupleslot(Tuplestorestate *state, bool forward, bool copy, TupleTableSlot *slot)
Definition: tuplestore.c:1078
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:425
static Datum slot_getattr(TupleTableSlot *slot, int attnum, bool *isnull)
Definition: tuptable.h:381
String * makeString(char *str)
Definition: value.c:63
@ WALRCV_OK_TUPLES
Definition: walreceiver.h:203
static void walrcv_clear_result(WalRcvExecResult *walres)
Definition: walreceiver.h:436
#define walrcv_exec(conn, exec, nRetTypes, retTypes)
Definition: walreceiver.h:430

References appendStringInfoChar(), appendStringInfoString(), Assert(), StringInfoData::data, ereport, errcode(), errmsg_plural(), ERROR, ExecClearTuple(), ExecDropSingleTupleTableSlot(), get_publications_str(), list_copy(), list_delete(), list_length(), MakeSingleTupleTableSlot(), makeString(), makeStringInfo(), NIL, pfree(), res, slot_getattr(), TextDatumGetCString, TTSOpsMinimalTuple, tuplestore_gettupleslot(), walrcv_clear_result(), walrcv_exec, WALRCV_OK_TUPLES, WARNING, and wrconn.

Referenced by AlterSubscription_refresh(), and CreateSubscription().

◆ CreateSubscription()

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

Definition at line 509 of file subscriptioncmds.c.

511 {
512  Relation rel;
513  ObjectAddress myself;
514  Oid subid;
515  bool nulls[Natts_pg_subscription];
516  Datum values[Natts_pg_subscription];
517  Oid owner = GetUserId();
518  HeapTuple tup;
519  char *conninfo;
520  char originname[NAMEDATALEN];
521  List *publications;
522  bits32 supported_opts;
523  SubOpts opts = {0};
524 
525  /*
526  * Parse and check options.
527  *
528  * Connection and publication should not be specified here.
529  */
530  supported_opts = (SUBOPT_CONNECT | SUBOPT_ENABLED | SUBOPT_CREATE_SLOT |
535  parse_subscription_options(pstate, stmt->options, supported_opts, &opts);
536 
537  /*
538  * Since creating a replication slot is not transactional, rolling back
539  * the transaction leaves the created replication slot. So we cannot run
540  * CREATE SUBSCRIPTION inside a transaction block if creating a
541  * replication slot.
542  */
543  if (opts.create_slot)
544  PreventInTransactionBlock(isTopLevel, "CREATE SUBSCRIPTION ... WITH (create_slot = true)");
545 
546  if (!superuser())
547  ereport(ERROR,
548  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
549  errmsg("must be superuser to create subscriptions")));
550 
551  /*
552  * If built with appropriate switch, whine when regression-testing
553  * conventions for subscription names are violated.
554  */
555 #ifdef ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS
556  if (strncmp(stmt->subname, "regress_", 8) != 0)
557  elog(WARNING, "subscriptions created by regression test cases should have names starting with \"regress_\"");
558 #endif
559 
560  rel = table_open(SubscriptionRelationId, RowExclusiveLock);
561 
562  /* Check if name is used */
563  subid = GetSysCacheOid2(SUBSCRIPTIONNAME, Anum_pg_subscription_oid,
565  if (OidIsValid(subid))
566  {
567  ereport(ERROR,
569  errmsg("subscription \"%s\" already exists",
570  stmt->subname)));
571  }
572 
573  if (!IsSet(opts.specified_opts, SUBOPT_SLOT_NAME) &&
574  opts.slot_name == NULL)
575  opts.slot_name = stmt->subname;
576 
577  /* The default for synchronous_commit of subscriptions is off. */
578  if (opts.synchronous_commit == NULL)
579  opts.synchronous_commit = "off";
580 
581  conninfo = stmt->conninfo;
582  publications = stmt->publication;
583 
584  /* Load the library providing us libpq calls. */
585  load_file("libpqwalreceiver", false);
586 
587  /* Check the connection info string. */
588  walrcv_check_conninfo(conninfo);
589 
590  /* Everything ok, form a new tuple. */
591  memset(values, 0, sizeof(values));
592  memset(nulls, false, sizeof(nulls));
593 
594  subid = GetNewOidWithIndex(rel, SubscriptionObjectIndexId,
595  Anum_pg_subscription_oid);
596  values[Anum_pg_subscription_oid - 1] = ObjectIdGetDatum(subid);
597  values[Anum_pg_subscription_subdbid - 1] = ObjectIdGetDatum(MyDatabaseId);
598  values[Anum_pg_subscription_subskiplsn - 1] = LSNGetDatum(InvalidXLogRecPtr);
599  values[Anum_pg_subscription_subname - 1] =
601  values[Anum_pg_subscription_subowner - 1] = ObjectIdGetDatum(owner);
602  values[Anum_pg_subscription_subenabled - 1] = BoolGetDatum(opts.enabled);
603  values[Anum_pg_subscription_subbinary - 1] = BoolGetDatum(opts.binary);
604  values[Anum_pg_subscription_substream - 1] = BoolGetDatum(opts.streaming);
605  values[Anum_pg_subscription_subtwophasestate - 1] =
606  CharGetDatum(opts.twophase ?
609  values[Anum_pg_subscription_subdisableonerr - 1] = BoolGetDatum(opts.disableonerr);
610  values[Anum_pg_subscription_subconninfo - 1] =
611  CStringGetTextDatum(conninfo);
612  if (opts.slot_name)
613  values[Anum_pg_subscription_subslotname - 1] =
615  else
616  nulls[Anum_pg_subscription_subslotname - 1] = true;
617  values[Anum_pg_subscription_subsynccommit - 1] =
618  CStringGetTextDatum(opts.synchronous_commit);
619  values[Anum_pg_subscription_subpublications - 1] =
620  publicationListToArray(publications);
621 
622  tup = heap_form_tuple(RelationGetDescr(rel), values, nulls);
623 
624  /* Insert tuple into catalog. */
625  CatalogTupleInsert(rel, tup);
626  heap_freetuple(tup);
627 
628  recordDependencyOnOwner(SubscriptionRelationId, subid, owner);
629 
630  snprintf(originname, sizeof(originname), "pg_%u", subid);
631  replorigin_create(originname);
632 
633  /*
634  * Connect to remote side to execute requested commands and fetch table
635  * info.
636  */
637  if (opts.connect)
638  {
639  char *err;
641  List *tables;
642  ListCell *lc;
643  char table_state;
644 
645  /* Try to connect to the publisher. */
646  wrconn = walrcv_connect(conninfo, true, stmt->subname, &err);
647  if (!wrconn)
648  ereport(ERROR,
649  (errcode(ERRCODE_CONNECTION_FAILURE),
650  errmsg("could not connect to the publisher: %s", err)));
651 
652  PG_TRY();
653  {
654  check_publications(wrconn, publications);
655 
656  /*
657  * Set sync state based on if we were asked to do data copy or
658  * not.
659  */
660  table_state = opts.copy_data ? SUBREL_STATE_INIT : SUBREL_STATE_READY;
661 
662  /*
663  * Get the table list from publisher and build local table status
664  * info.
665  */
666  tables = fetch_table_list(wrconn, publications);
667  foreach(lc, tables)
668  {
669  RangeVar *rv = (RangeVar *) lfirst(lc);
670  Oid relid;
671 
672  relid = RangeVarGetRelid(rv, AccessShareLock, false);
673 
674  /* Check for supported relkind. */
676  rv->schemaname, rv->relname);
677 
678  AddSubscriptionRelState(subid, relid, table_state,
680  }
681 
682  /*
683  * If requested, create permanent slot for the subscription. We
684  * won't use the initial snapshot for anything, so no need to
685  * export it.
686  */
687  if (opts.create_slot)
688  {
689  bool twophase_enabled = false;
690 
691  Assert(opts.slot_name);
692 
693  /*
694  * Even if two_phase is set, don't create the slot with
695  * two-phase enabled. Will enable it once all the tables are
696  * synced and ready. This avoids race-conditions like prepared
697  * transactions being skipped due to changes not being applied
698  * due to checks in should_apply_changes_for_rel() when
699  * tablesync for the corresponding tables are in progress. See
700  * comments atop worker.c.
701  *
702  * Note that if tables were specified but copy_data is false
703  * then it is safe to enable two_phase up-front because those
704  * tables are already initially in READY state. When the
705  * subscription has no tables, we leave the twophase state as
706  * PENDING, to allow ALTER SUBSCRIPTION ... REFRESH
707  * PUBLICATION to work.
708  */
709  if (opts.twophase && !opts.copy_data && tables != NIL)
710  twophase_enabled = true;
711 
712  walrcv_create_slot(wrconn, opts.slot_name, false, twophase_enabled,
713  CRS_NOEXPORT_SNAPSHOT, NULL);
714 
715  if (twophase_enabled)
717 
718  ereport(NOTICE,
719  (errmsg("created replication slot \"%s\" on publisher",
720  opts.slot_name)));
721  }
722  }
723  PG_FINALLY();
724  {
726  }
727  PG_END_TRY();
728  }
729  else
731  /* translator: %s is an SQL ALTER statement */
732  (errmsg("tables were not subscribed, you will have to run %s to subscribe the tables",
733  "ALTER SUBSCRIPTION ... REFRESH PUBLICATION")));
734 
736 
738 
739  if (opts.enabled)
741 
742  ObjectAddressSet(myself, SubscriptionRelationId, subid);
743 
744  InvokeObjectPostCreateHook(SubscriptionRelationId, subid, 0);
745 
746  return myself;
747 }
#define OidIsValid(objectId)
Definition: c.h:710
Oid GetNewOidWithIndex(Relation relation, Oid indexId, AttrNumber oidcolumn)
Definition: catalog.c:391
#define NOTICE
Definition: elog.h:29
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:221
#define InvokeObjectPostCreateHook(classId, objectId, subId)
Definition: objectaccess.h:171
RepOriginId replorigin_create(const char *roname)
Definition: origin.c:240
void recordDependencyOnOwner(Oid classId, Oid objectId, Oid owner)
Definition: pg_shdepend.c:164
#define LOGICALREP_TWOPHASE_STATE_DISABLED
#define LOGICALREP_TWOPHASE_STATE_PENDING
void pgstat_create_subscription(Oid subid)
#define CharGetDatum(X)
Definition: postgres.h:460
#define SUBOPT_CREATE_SLOT
#define SUBOPT_TWOPHASE_COMMIT
#define SUBOPT_CONNECT
#define GetSysCacheOid2(cacheId, oidcol, key1, key2)
Definition: syscache.h:199
void UpdateTwoPhaseState(Oid suboid, char new_state)
Definition: tablesync.c:1540
#define walrcv_create_slot(conn, slotname, temporary, two_phase, snapshot_action, lsn)
Definition: walreceiver.h:426
@ CRS_NOEXPORT_SNAPSHOT
Definition: walsender.h:23

References AccessShareLock, AddSubscriptionRelState(), ApplyLauncherWakeupAtCommit(), Assert(), BoolGetDatum, CatalogTupleInsert(), CharGetDatum, check_publications(), CheckSubscriptionRelkind(), CreateSubscriptionStmt::conninfo, CRS_NOEXPORT_SNAPSHOT, CStringGetDatum, CStringGetTextDatum, DirectFunctionCall1, elog, 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, LSNGetDatum, MyDatabaseId, NAMEDATALEN, namein(), NIL, NOTICE, ObjectAddressSet, ObjectIdGetDatum, OidIsValid, CreateSubscriptionStmt::options, opts, parse_subscription_options(), PG_END_TRY, PG_FINALLY, PG_TRY, pgstat_create_subscription(), PreventInTransactionBlock(), CreateSubscriptionStmt::publication, publicationListToArray(), RangeVarGetRelid, recordDependencyOnOwner(), RelationGetDescr, RangeVar::relname, replorigin_create(), RowExclusiveLock, RangeVar::schemaname, snprintf, CreateSubscriptionStmt::subname, SUBOPT_BINARY, SUBOPT_CONNECT, SUBOPT_COPY_DATA, SUBOPT_CREATE_SLOT, SUBOPT_DISABLE_ON_ERR, SUBOPT_ENABLED, SUBOPT_SLOT_NAME, SUBOPT_STREAMING, SUBOPT_SYNCHRONOUS_COMMIT, SUBOPT_TWOPHASE_COMMIT, SUBSCRIPTIONNAME, superuser(), table_close(), table_open(), UpdateTwoPhaseState(), values, walrcv_check_conninfo, walrcv_connect, walrcv_create_slot, walrcv_disconnect, WARNING, and wrconn.

Referenced by ProcessUtilitySlow().

◆ DropSubscription()

void DropSubscription ( DropSubscriptionStmt stmt,
bool  isTopLevel 
)

Definition at line 1321 of file subscriptioncmds.c.

1322 {
1323  Relation rel;
1324  ObjectAddress myself;
1325  HeapTuple tup;
1326  Oid subid;
1327  Datum datum;
1328  bool isnull;
1329  char *subname;
1330  char *conninfo;
1331  char *slotname;
1332  List *subworkers;
1333  ListCell *lc;
1334  char originname[NAMEDATALEN];
1335  char *err = NULL;
1337  Form_pg_subscription form;
1338  List *rstates;
1339 
1340  /*
1341  * Lock pg_subscription with AccessExclusiveLock to ensure that the
1342  * launcher doesn't restart new worker during dropping the subscription
1343  */
1344  rel = table_open(SubscriptionRelationId, AccessExclusiveLock);
1345 
1347  CStringGetDatum(stmt->subname));
1348 
1349  if (!HeapTupleIsValid(tup))
1350  {
1351  table_close(rel, NoLock);
1352 
1353  if (!stmt->missing_ok)
1354  ereport(ERROR,
1355  (errcode(ERRCODE_UNDEFINED_OBJECT),
1356  errmsg("subscription \"%s\" does not exist",
1357  stmt->subname)));
1358  else
1359  ereport(NOTICE,
1360  (errmsg("subscription \"%s\" does not exist, skipping",
1361  stmt->subname)));
1362 
1363  return;
1364  }
1365 
1366  form = (Form_pg_subscription) GETSTRUCT(tup);
1367  subid = form->oid;
1368 
1369  /* must be owner */
1370  if (!pg_subscription_ownercheck(subid, GetUserId()))
1372  stmt->subname);
1373 
1374  /* DROP hook for the subscription being removed */
1375  InvokeObjectDropHook(SubscriptionRelationId, subid, 0);
1376 
1377  /*
1378  * Lock the subscription so nobody else can do anything with it (including
1379  * the replication workers).
1380  */
1381  LockSharedObject(SubscriptionRelationId, subid, 0, AccessExclusiveLock);
1382 
1383  /* Get subname */
1384  datum = SysCacheGetAttr(SUBSCRIPTIONOID, tup,
1385  Anum_pg_subscription_subname, &isnull);
1386  Assert(!isnull);
1387  subname = pstrdup(NameStr(*DatumGetName(datum)));
1388 
1389  /* Get conninfo */
1390  datum = SysCacheGetAttr(SUBSCRIPTIONOID, tup,
1391  Anum_pg_subscription_subconninfo, &isnull);
1392  Assert(!isnull);
1393  conninfo = TextDatumGetCString(datum);
1394 
1395  /* Get slotname */
1396  datum = SysCacheGetAttr(SUBSCRIPTIONOID, tup,
1397  Anum_pg_subscription_subslotname, &isnull);
1398  if (!isnull)
1399  slotname = pstrdup(NameStr(*DatumGetName(datum)));
1400  else
1401  slotname = NULL;
1402 
1403  /*
1404  * Since dropping a replication slot is not transactional, the replication
1405  * slot stays dropped even if the transaction rolls back. So we cannot
1406  * run DROP SUBSCRIPTION inside a transaction block if dropping the
1407  * replication slot. Also, in this case, we report a message for dropping
1408  * the subscription to the cumulative stats system.
1409  *
1410  * XXX The command name should really be something like "DROP SUBSCRIPTION
1411  * of a subscription that is associated with a replication slot", but we
1412  * don't have the proper facilities for that.
1413  */
1414  if (slotname)
1415  PreventInTransactionBlock(isTopLevel, "DROP SUBSCRIPTION");
1416 
1417  ObjectAddressSet(myself, SubscriptionRelationId, subid);
1418  EventTriggerSQLDropAddObject(&myself, true, true);
1419 
1420  /* Remove the tuple from catalog. */
1421  CatalogTupleDelete(rel, &tup->t_self);
1422 
1423  ReleaseSysCache(tup);
1424 
1425  /*
1426  * Stop all the subscription workers immediately.
1427  *
1428  * This is necessary if we are dropping the replication slot, so that the
1429  * slot becomes accessible.
1430  *
1431  * It is also necessary if the subscription is disabled and was disabled
1432  * in the same transaction. Then the workers haven't seen the disabling
1433  * yet and will still be running, leading to hangs later when we want to
1434  * drop the replication origin. If the subscription was disabled before
1435  * this transaction, then there shouldn't be any workers left, so this
1436  * won't make a difference.
1437  *
1438  * New workers won't be started because we hold an exclusive lock on the
1439  * subscription till the end of the transaction.
1440  */
1441  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
1442  subworkers = logicalrep_workers_find(subid, false);
1443  LWLockRelease(LogicalRepWorkerLock);
1444  foreach(lc, subworkers)
1445  {
1447 
1449  }
1450  list_free(subworkers);
1451 
1452  /*
1453  * Cleanup of tablesync replication origins.
1454  *
1455  * Any READY-state relations would already have dealt with clean-ups.
1456  *
1457  * Note that the state can't change because we have already stopped both
1458  * the apply and tablesync workers and they can't restart because of
1459  * exclusive lock on the subscription.
1460  */
1461  rstates = GetSubscriptionNotReadyRelations(subid);
1462  foreach(lc, rstates)
1463  {
1465  Oid relid = rstate->relid;
1466 
1467  /* Only cleanup resources of tablesync workers */
1468  if (!OidIsValid(relid))
1469  continue;
1470 
1471  /*
1472  * Drop the tablesync's origin tracking if exists.
1473  *
1474  * It is possible that the origin is not yet created for tablesync
1475  * worker so passing missing_ok = true. This can happen for the states
1476  * before SUBREL_STATE_FINISHEDCOPY.
1477  */
1478  ReplicationOriginNameForTablesync(subid, relid, originname,
1479  sizeof(originname));
1480  replorigin_drop_by_name(originname, true, false);
1481  }
1482 
1483  /* Clean up dependencies */
1484  deleteSharedDependencyRecordsFor(SubscriptionRelationId, subid, 0);
1485 
1486  /* Remove any associated relation synchronization states. */
1488 
1489  /* Remove the origin tracking if exists. */
1490  snprintf(originname, sizeof(originname), "pg_%u", subid);
1491  replorigin_drop_by_name(originname, true, false);
1492 
1493  /*
1494  * If there is no slot associated with the subscription, we can finish
1495  * here.
1496  */
1497  if (!slotname && rstates == NIL)
1498  {
1499  table_close(rel, NoLock);
1500  return;
1501  }
1502 
1503  /*
1504  * Try to acquire the connection necessary for dropping slots.
1505  *
1506  * Note: If the slotname is NONE/NULL then we allow the command to finish
1507  * and users need to manually cleanup the apply and tablesync worker slots
1508  * later.
1509  *
1510  * This has to be at the end because otherwise if there is an error while
1511  * doing the database operations we won't be able to rollback dropped
1512  * slot.
1513  */
1514  load_file("libpqwalreceiver", false);
1515 
1516  wrconn = walrcv_connect(conninfo, true, subname, &err);
1517  if (wrconn == NULL)
1518  {
1519  if (!slotname)
1520  {
1521  /* be tidy */
1522  list_free(rstates);
1523  table_close(rel, NoLock);
1524  return;
1525  }
1526  else
1527  {
1528  ReportSlotConnectionError(rstates, subid, slotname, err);
1529  }
1530  }
1531 
1532  PG_TRY();
1533  {
1534  foreach(lc, rstates)
1535  {
1537  Oid relid = rstate->relid;
1538 
1539  /* Only cleanup resources of tablesync workers */
1540  if (!OidIsValid(relid))
1541  continue;
1542 
1543  /*
1544  * Drop the tablesync slots associated with removed tables.
1545  *
1546  * For SYNCDONE/READY states, the tablesync slot is known to have
1547  * already been dropped by the tablesync worker.
1548  *
1549  * For other states, there is no certainty, maybe the slot does
1550  * not exist yet. Also, if we fail after removing some of the
1551  * slots, next time, it will again try to drop already dropped
1552  * slots and fail. For these reasons, we allow missing_ok = true
1553  * for the drop.
1554  */
1555  if (rstate->state != SUBREL_STATE_SYNCDONE)
1556  {
1557  char syncslotname[NAMEDATALEN] = {0};
1558 
1559  ReplicationSlotNameForTablesync(subid, relid, syncslotname,
1560  sizeof(syncslotname));
1561  ReplicationSlotDropAtPubNode(wrconn, syncslotname, true);
1562  }
1563  }
1564 
1565  list_free(rstates);
1566 
1567  /*
1568  * If there is a slot associated with the subscription, then drop the
1569  * replication slot at the publisher.
1570  */
1571  if (slotname)
1572  ReplicationSlotDropAtPubNode(wrconn, slotname, false);
1573  }
1574  PG_FINALLY();
1575  {
1577  }
1578  PG_END_TRY();
1579 
1580  /*
1581  * Tell the cumulative stats system that the subscription is getting
1582  * dropped. We can safely report dropping the subscription statistics here
1583  * if the subscription is associated with a replication slot since we
1584  * cannot run DROP SUBSCRIPTION inside a transaction block. Subscription
1585  * statistics will be removed later by (auto)vacuum either if it's not
1586  * associated with a replication slot or if the message for dropping the
1587  * subscription gets lost.
1588  */
1589  if (slotname)
1590  pgstat_drop_subscription(subid);
1591 
1592  table_close(rel, NoLock);
1593 }
void EventTriggerSQLDropAddObject(const ObjectAddress *object, bool original, bool normal)
void CatalogTupleDelete(Relation heapRel, ItemPointer tid)
Definition: indexing.c:350
List * logicalrep_workers_find(Oid subid, bool only_running)
Definition: launcher.c:242
void list_free(List *list)
Definition: list.c:1505
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1196
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1800
@ LW_SHARED
Definition: lwlock.h:105
char * pstrdup(const char *in)
Definition: mcxt.c:1305
#define InvokeObjectDropHook(classId, objectId, subId)
Definition: objectaccess.h:180
void deleteSharedDependencyRecordsFor(Oid classId, Oid objectId, int32 objectSubId)
Definition: pg_shdepend.c:1001
List * GetSubscriptionNotReadyRelations(Oid subid)
NameData subname
void pgstat_drop_subscription(Oid subid)
#define DatumGetName(X)
Definition: postgres.h:629
#define InvalidOid
Definition: postgres_ext.h:36
static void ReportSlotConnectionError(List *rstates, Oid subid, char *slotname, char *err)
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1221
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1434
HeapTuple SearchSysCache2(int cacheId, Datum key1, Datum key2)
Definition: syscache.c:1184

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, pgstat_drop_subscription(), PreventInTransactionBlock(), pstrdup(), ReleaseSysCache(), SubscriptionRelState::relid, LogicalRepWorker::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().

◆ fetch_table_list()

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

Definition at line 1759 of file subscriptioncmds.c.

1760 {
1762  StringInfoData cmd;
1763  TupleTableSlot *slot;
1764  Oid tableRow[2] = {TEXTOID, TEXTOID};
1765  List *tablelist = NIL;
1766 
1767  initStringInfo(&cmd);
1768  appendStringInfoString(&cmd, "SELECT DISTINCT t.schemaname, t.tablename\n"
1769  " FROM pg_catalog.pg_publication_tables t\n"
1770  " WHERE t.pubname IN (");
1771  get_publications_str(publications, &cmd, true);
1772  appendStringInfoChar(&cmd, ')');
1773 
1774  res = walrcv_exec(wrconn, cmd.data, 2, tableRow);
1775  pfree(cmd.data);
1776 
1777  if (res->status != WALRCV_OK_TUPLES)
1778  ereport(ERROR,
1779  (errcode(ERRCODE_CONNECTION_FAILURE),
1780  errmsg("could not receive list of replicated tables from the publisher: %s",
1781  res->err)));
1782 
1783  /* Process tables. */
1784  slot = MakeSingleTupleTableSlot(res->tupledesc, &TTSOpsMinimalTuple);
1785  while (tuplestore_gettupleslot(res->tuplestore, true, false, slot))
1786  {
1787  char *nspname;
1788  char *relname;
1789  bool isnull;
1790  RangeVar *rv;
1791 
1792  nspname = TextDatumGetCString(slot_getattr(slot, 1, &isnull));
1793  Assert(!isnull);
1794  relname = TextDatumGetCString(slot_getattr(slot, 2, &isnull));
1795  Assert(!isnull);
1796 
1797  rv = makeRangeVar(nspname, relname, -1);
1798  tablelist = lappend(tablelist, rv);
1799 
1800  ExecClearTuple(slot);
1801  }
1803 
1805 
1806  return tablelist;
1807 }
List * lappend(List *list, void *datum)
Definition: list.c:336
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:423
NameData relname
Definition: pg_class.h:38
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59

References appendStringInfoChar(), appendStringInfoString(), Assert(), StringInfoData::data, ereport, errcode(), errmsg(), ERROR, ExecClearTuple(), ExecDropSingleTupleTableSlot(), get_publications_str(), initStringInfo(), lappend(), makeRangeVar(), MakeSingleTupleTableSlot(), NIL, pfree(), relname, res, slot_getattr(), TextDatumGetCString, TTSOpsMinimalTuple, tuplestore_gettupleslot(), walrcv_clear_result(), walrcv_exec, WALRCV_OK_TUPLES, and wrconn.

Referenced by AlterSubscription_refresh(), and CreateSubscription().

◆ get_publications_str()

static void get_publications_str ( List publications,
StringInfo  dest,
bool  quote_literal 
)
static

Definition at line 381 of file subscriptioncmds.c.

382 {
383  ListCell *lc;
384  bool first = true;
385 
386  Assert(list_length(publications) > 0);
387 
388  foreach(lc, publications)
389  {
390  char *pubname = strVal(lfirst(lc));
391 
392  if (first)
393  first = false;
394  else
396 
397  if (quote_literal)
399  else
400  {
402  appendStringInfoString(dest, pubname);
404  }
405  }
406 }
char * quote_literal_cstr(const char *rawstr)
Definition: quote.c:102
Datum quote_literal(PG_FUNCTION_ARGS)
Definition: quote.c:77

References appendStringInfoChar(), appendStringInfoString(), Assert(), generate_unaccent_rules::dest, lfirst, list_length(), quote_literal(), quote_literal_cstr(), and strVal.

Referenced by check_publications(), and fetch_table_list().

◆ merge_publications()

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

Definition at line 1898 of file subscriptioncmds.c.

1899 {
1900  ListCell *lc;
1901 
1902  oldpublist = list_copy(oldpublist);
1903 
1904  check_duplicates_in_publist(newpublist, NULL);
1905 
1906  foreach(lc, newpublist)
1907  {
1908  char *name = strVal(lfirst(lc));
1909  ListCell *lc2;
1910  bool found = false;
1911 
1912  foreach(lc2, oldpublist)
1913  {
1914  char *pubname = strVal(lfirst(lc2));
1915 
1916  if (strcmp(name, pubname) == 0)
1917  {
1918  found = true;
1919  if (addpub)
1920  ereport(ERROR,
1922  errmsg("publication \"%s\" is already in subscription \"%s\"",
1923  name, subname)));
1924  else
1925  oldpublist = foreach_delete_current(oldpublist, lc2);
1926 
1927  break;
1928  }
1929  }
1930 
1931  if (addpub && !found)
1932  oldpublist = lappend(oldpublist, makeString(name));
1933  else if (!addpub && !found)
1934  ereport(ERROR,
1935  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1936  errmsg("publication \"%s\" is not in subscription \"%s\"",
1937  name, subname)));
1938  }
1939 
1940  /*
1941  * XXX Probably no strong reason for this, but for now it's to make ALTER
1942  * SUBSCRIPTION ... DROP PUBLICATION consistent with SET PUBLICATION.
1943  */
1944  if (!oldpublist)
1945  ereport(ERROR,
1946  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1947  errmsg("cannot drop all the publications from a subscription")));
1948 
1949  return oldpublist;
1950 }
#define foreach_delete_current(lst, cell)
Definition: pg_list.h:369
static void check_duplicates_in_publist(List *publist, Datum *datums)

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

Referenced by AlterSubscription().

◆ parse_subscription_options()

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

Definition at line 105 of file subscriptioncmds.c.

107 {
108  ListCell *lc;
109 
110  /* Start out with cleared opts. */
111  memset(opts, 0, sizeof(SubOpts));
112 
113  /* caller must expect some option */
114  Assert(supported_opts != 0);
115 
116  /* If connect option is supported, these others also need to be. */
117  Assert(!IsSet(supported_opts, SUBOPT_CONNECT) ||
118  IsSet(supported_opts, SUBOPT_ENABLED | SUBOPT_CREATE_SLOT |
120 
121  /* Set default values for the boolean supported options. */
122  if (IsSet(supported_opts, SUBOPT_CONNECT))
123  opts->connect = true;
124  if (IsSet(supported_opts, SUBOPT_ENABLED))
125  opts->enabled = true;
126  if (IsSet(supported_opts, SUBOPT_CREATE_SLOT))
127  opts->create_slot = true;
128  if (IsSet(supported_opts, SUBOPT_COPY_DATA))
129  opts->copy_data = true;
130  if (IsSet(supported_opts, SUBOPT_REFRESH))
131  opts->refresh = true;
132  if (IsSet(supported_opts, SUBOPT_BINARY))
133  opts->binary = false;
134  if (IsSet(supported_opts, SUBOPT_STREAMING))
135  opts->streaming = false;
136  if (IsSet(supported_opts, SUBOPT_TWOPHASE_COMMIT))
137  opts->twophase = false;
138  if (IsSet(supported_opts, SUBOPT_DISABLE_ON_ERR))
139  opts->disableonerr = false;
140 
141  /* Parse options */
142  foreach(lc, stmt_options)
143  {
144  DefElem *defel = (DefElem *) lfirst(lc);
145 
146  if (IsSet(supported_opts, SUBOPT_CONNECT) &&
147  strcmp(defel->defname, "connect") == 0)
148  {
149  if (IsSet(opts->specified_opts, SUBOPT_CONNECT))
150  errorConflictingDefElem(defel, pstate);
151 
152  opts->specified_opts |= SUBOPT_CONNECT;
153  opts->connect = defGetBoolean(defel);
154  }
155  else if (IsSet(supported_opts, SUBOPT_ENABLED) &&
156  strcmp(defel->defname, "enabled") == 0)
157  {
158  if (IsSet(opts->specified_opts, SUBOPT_ENABLED))
159  errorConflictingDefElem(defel, pstate);
160 
161  opts->specified_opts |= SUBOPT_ENABLED;
162  opts->enabled = defGetBoolean(defel);
163  }
164  else if (IsSet(supported_opts, SUBOPT_CREATE_SLOT) &&
165  strcmp(defel->defname, "create_slot") == 0)
166  {
167  if (IsSet(opts->specified_opts, SUBOPT_CREATE_SLOT))
168  errorConflictingDefElem(defel, pstate);
169 
170  opts->specified_opts |= SUBOPT_CREATE_SLOT;
171  opts->create_slot = defGetBoolean(defel);
172  }
173  else if (IsSet(supported_opts, SUBOPT_SLOT_NAME) &&
174  strcmp(defel->defname, "slot_name") == 0)
175  {
176  if (IsSet(opts->specified_opts, SUBOPT_SLOT_NAME))
177  errorConflictingDefElem(defel, pstate);
178 
179  opts->specified_opts |= SUBOPT_SLOT_NAME;
180  opts->slot_name = defGetString(defel);
181 
182  /* Setting slot_name = NONE is treated as no slot name. */
183  if (strcmp(opts->slot_name, "none") == 0)
184  opts->slot_name = NULL;
185  else
187  }
188  else if (IsSet(supported_opts, SUBOPT_COPY_DATA) &&
189  strcmp(defel->defname, "copy_data") == 0)
190  {
191  if (IsSet(opts->specified_opts, SUBOPT_COPY_DATA))
192  errorConflictingDefElem(defel, pstate);
193 
194  opts->specified_opts |= SUBOPT_COPY_DATA;
195  opts->copy_data = defGetBoolean(defel);
196  }
197  else if (IsSet(supported_opts, SUBOPT_SYNCHRONOUS_COMMIT) &&
198  strcmp(defel->defname, "synchronous_commit") == 0)
199  {
200  if (IsSet(opts->specified_opts, SUBOPT_SYNCHRONOUS_COMMIT))
201  errorConflictingDefElem(defel, pstate);
202 
203  opts->specified_opts |= SUBOPT_SYNCHRONOUS_COMMIT;
204  opts->synchronous_commit = defGetString(defel);
205 
206  /* Test if the given value is valid for synchronous_commit GUC. */
207  (void) set_config_option("synchronous_commit", opts->synchronous_commit,
209  false, 0, false);
210  }
211  else if (IsSet(supported_opts, SUBOPT_REFRESH) &&
212  strcmp(defel->defname, "refresh") == 0)
213  {
214  if (IsSet(opts->specified_opts, SUBOPT_REFRESH))
215  errorConflictingDefElem(defel, pstate);
216 
217  opts->specified_opts |= SUBOPT_REFRESH;
218  opts->refresh = defGetBoolean(defel);
219  }
220  else if (IsSet(supported_opts, SUBOPT_BINARY) &&
221  strcmp(defel->defname, "binary") == 0)
222  {
223  if (IsSet(opts->specified_opts, SUBOPT_BINARY))
224  errorConflictingDefElem(defel, pstate);
225 
226  opts->specified_opts |= SUBOPT_BINARY;
227  opts->binary = defGetBoolean(defel);
228  }
229  else if (IsSet(supported_opts, SUBOPT_STREAMING) &&
230  strcmp(defel->defname, "streaming") == 0)
231  {
232  if (IsSet(opts->specified_opts, SUBOPT_STREAMING))
233  errorConflictingDefElem(defel, pstate);
234 
235  opts->specified_opts |= SUBOPT_STREAMING;
236  opts->streaming = defGetBoolean(defel);
237  }
238  else if (strcmp(defel->defname, "two_phase") == 0)
239  {
240  /*
241  * Do not allow toggling of two_phase option. Doing so could cause
242  * missing of transactions and lead to an inconsistent replica.
243  * See comments atop worker.c
244  *
245  * Note: Unsupported twophase indicates that this call originated
246  * from AlterSubscription.
247  */
248  if (!IsSet(supported_opts, SUBOPT_TWOPHASE_COMMIT))
249  ereport(ERROR,
250  (errcode(ERRCODE_SYNTAX_ERROR),
251  errmsg("unrecognized subscription parameter: \"%s\"", defel->defname)));
252 
253  if (IsSet(opts->specified_opts, SUBOPT_TWOPHASE_COMMIT))
254  errorConflictingDefElem(defel, pstate);
255 
256  opts->specified_opts |= SUBOPT_TWOPHASE_COMMIT;
257  opts->twophase = defGetBoolean(defel);
258  }
259  else if (IsSet(supported_opts, SUBOPT_DISABLE_ON_ERR) &&
260  strcmp(defel->defname, "disable_on_error") == 0)
261  {
262  if (IsSet(opts->specified_opts, SUBOPT_DISABLE_ON_ERR))
263  errorConflictingDefElem(defel, pstate);
264 
265  opts->specified_opts |= SUBOPT_DISABLE_ON_ERR;
266  opts->disableonerr = defGetBoolean(defel);
267  }
268  else if (IsSet(supported_opts, SUBOPT_LSN) &&
269  strcmp(defel->defname, "lsn") == 0)
270  {
271  char *lsn_str = defGetString(defel);
272  XLogRecPtr lsn;
273 
274  if (IsSet(opts->specified_opts, SUBOPT_LSN))
275  errorConflictingDefElem(defel, pstate);
276 
277  /* Setting lsn = NONE is treated as resetting LSN */
278  if (strcmp(lsn_str, "none") == 0)
279  lsn = InvalidXLogRecPtr;
280  else
281  {
282  /* Parse the argument as LSN */
284  CStringGetDatum(lsn_str)));
285 
286  if (XLogRecPtrIsInvalid(lsn))
287  ereport(ERROR,
288  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
289  errmsg("invalid WAL location (LSN): %s", lsn_str)));
290  }
291 
292  opts->specified_opts |= SUBOPT_LSN;
293  opts->lsn = lsn;
294  }
295  else
296  ereport(ERROR,
297  (errcode(ERRCODE_SYNTAX_ERROR),
298  errmsg("unrecognized subscription parameter: \"%s\"", defel->defname)));
299  }
300 
301  /*
302  * We've been explicitly asked to not connect, that requires some
303  * additional processing.
304  */
305  if (!opts->connect && IsSet(supported_opts, SUBOPT_CONNECT))
306  {
307  /* Check for incompatible options from the user. */
308  if (opts->enabled &&
309  IsSet(opts->specified_opts, SUBOPT_ENABLED))
310  ereport(ERROR,
311  (errcode(ERRCODE_SYNTAX_ERROR),
312  /*- translator: both %s are strings of the form "option = value" */
313  errmsg("%s and %s are mutually exclusive options",
314  "connect = false", "enabled = true")));
315 
316  if (opts->create_slot &&
317  IsSet(opts->specified_opts, SUBOPT_CREATE_SLOT))
318  ereport(ERROR,
319  (errcode(ERRCODE_SYNTAX_ERROR),
320  errmsg("%s and %s are mutually exclusive options",
321  "connect = false", "create_slot = true")));
322 
323  if (opts->copy_data &&
324  IsSet(opts->specified_opts, SUBOPT_COPY_DATA))
325  ereport(ERROR,
326  (errcode(ERRCODE_SYNTAX_ERROR),
327  errmsg("%s and %s are mutually exclusive options",
328  "connect = false", "copy_data = true")));
329 
330  /* Change the defaults of other options. */
331  opts->enabled = false;
332  opts->create_slot = false;
333  opts->copy_data = false;
334  }
335 
336  /*
337  * Do additional checking for disallowed combination when slot_name = NONE
338  * was used.
339  */
340  if (!opts->slot_name &&
341  IsSet(opts->specified_opts, SUBOPT_SLOT_NAME))
342  {
343  if (opts->enabled)
344  {
345  if (IsSet(opts->specified_opts, SUBOPT_ENABLED))
346  ereport(ERROR,
347  (errcode(ERRCODE_SYNTAX_ERROR),
348  /*- translator: both %s are strings of the form "option = value" */
349  errmsg("%s and %s are mutually exclusive options",
350  "slot_name = NONE", "enabled = true")));
351  else
352  ereport(ERROR,
353  (errcode(ERRCODE_SYNTAX_ERROR),
354  /*- translator: both %s are strings of the form "option = value" */
355  errmsg("subscription with %s must also set %s",
356  "slot_name = NONE", "enabled = false")));
357  }
358 
359  if (opts->create_slot)
360  {
361  if (IsSet(opts->specified_opts, SUBOPT_CREATE_SLOT))
362  ereport(ERROR,
363  (errcode(ERRCODE_SYNTAX_ERROR),
364  /*- translator: both %s are strings of the form "option = value" */
365  errmsg("%s and %s are mutually exclusive options",
366  "slot_name = NONE", "create_slot = true")));
367  else
368  ereport(ERROR,
369  (errcode(ERRCODE_SYNTAX_ERROR),
370  /*- translator: both %s are strings of the form "option = value" */
371  errmsg("subscription with %s must also set %s",
372  "slot_name = NONE", "create_slot = false")));
373  }
374  }
375 }
bool defGetBoolean(DefElem *def)
Definition: define.c:108
char * defGetString(DefElem *def)
Definition: define.c:49
void errorConflictingDefElem(DefElem *defel, ParseState *pstate)
Definition: define.c:352
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:7558
@ GUC_ACTION_SET
Definition: guc.h:194
@ PGC_S_TEST
Definition: guc.h:118
@ PGC_BACKEND
Definition: guc.h:74
Datum pg_lsn_in(PG_FUNCTION_ARGS)
Definition: pg_lsn.c:64
#define DatumGetLSN(X)
Definition: pg_lsn.h:21
bool ReplicationSlotValidateName(const char *name, int elevel)
Definition: slot.c:201
char * defname
Definition: parsenodes.h:765

References Assert(), CStringGetDatum, DatumGetLSN, defGetBoolean(), defGetString(), DefElem::defname, DirectFunctionCall1, ereport, errcode(), errmsg(), ERROR, errorConflictingDefElem(), GUC_ACTION_SET, InvalidXLogRecPtr, IsSet, lfirst, opts, pg_lsn_in(), PGC_BACKEND, PGC_S_TEST, ReplicationSlotValidateName(), set_config_option(), SUBOPT_BINARY, SUBOPT_CONNECT, SUBOPT_COPY_DATA, SUBOPT_CREATE_SLOT, SUBOPT_DISABLE_ON_ERR, SUBOPT_ENABLED, SUBOPT_LSN, SUBOPT_REFRESH, SUBOPT_SLOT_NAME, SUBOPT_STREAMING, SUBOPT_SYNCHRONOUS_COMMIT, SUBOPT_TWOPHASE_COMMIT, and XLogRecPtrIsInvalid.

Referenced by AlterSubscription(), and CreateSubscription().

◆ publicationListToArray()

static Datum publicationListToArray ( List publist)
static

Definition at line 478 of file subscriptioncmds.c.

479 {
480  ArrayType *arr;
481  Datum *datums;
482  MemoryContext memcxt;
483  MemoryContext oldcxt;
484 
485  /* Create memory context for temporary allocations. */
487  "publicationListToArray to array",
489  oldcxt = MemoryContextSwitchTo(memcxt);
490 
491  datums = (Datum *) palloc(sizeof(Datum) * list_length(publist));
492 
493  check_duplicates_in_publist(publist, datums);
494 
495  MemoryContextSwitchTo(oldcxt);
496 
497  arr = construct_array(datums, list_length(publist),
498  TEXTOID, -1, false, TYPALIGN_INT);
499 
500  MemoryContextDelete(memcxt);
501 
502  return PointerGetDatum(arr);
503 }
ArrayType * construct_array(Datum *elems, int nelems, Oid elmtype, int elmlen, bool elmbyval, char elmalign)
Definition: arrayfuncs.c:3319
MemoryContext CurrentMemoryContext
Definition: mcxt.c:42
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:218
#define AllocSetContextCreate
Definition: memutils.h:173
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:197
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define PointerGetDatum(X)
Definition: postgres.h:600

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

Referenced by AlterSubscription(), and CreateSubscription().

◆ ReplicationSlotDropAtPubNode()

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

Definition at line 1603 of file subscriptioncmds.c.

1604 {
1605  StringInfoData cmd;
1606 
1607  Assert(wrconn);
1608 
1609  load_file("libpqwalreceiver", false);
1610 
1611  initStringInfo(&cmd);
1612  appendStringInfo(&cmd, "DROP_REPLICATION_SLOT %s WAIT", quote_identifier(slotname));
1613 
1614  PG_TRY();
1615  {
1617 
1618  res = walrcv_exec(wrconn, cmd.data, 0, NULL);
1619 
1620  if (res->status == WALRCV_OK_COMMAND)
1621  {
1622  /* NOTICE. Success. */
1623  ereport(NOTICE,
1624  (errmsg("dropped replication slot \"%s\" on publisher",
1625  slotname)));
1626  }
1627  else if (res->status == WALRCV_ERROR &&
1628  missing_ok &&
1629  res->sqlstate == ERRCODE_UNDEFINED_OBJECT)
1630  {
1631  /* LOG. Error, but missing_ok = true. */
1632  ereport(LOG,
1633  (errmsg("could not drop replication slot \"%s\" on publisher: %s",
1634  slotname, res->err)));
1635  }
1636  else
1637  {
1638  /* ERROR. */
1639  ereport(ERROR,
1640  (errcode(ERRCODE_CONNECTION_FAILURE),
1641  errmsg("could not drop replication slot \"%s\" on publisher: %s",
1642  slotname, res->err)));
1643  }
1644 
1646  }
1647  PG_FINALLY();
1648  {
1649  pfree(cmd.data);
1650  }
1651  PG_END_TRY();
1652 }
#define LOG
Definition: elog.h:25
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:12192
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
@ WALRCV_OK_COMMAND
Definition: walreceiver.h:201
@ WALRCV_ERROR
Definition: walreceiver.h:200

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

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

◆ ReportSlotConnectionError()

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

Definition at line 1815 of file subscriptioncmds.c.

1816 {
1817  ListCell *lc;
1818 
1819  foreach(lc, rstates)
1820  {
1822  Oid relid = rstate->relid;
1823 
1824  /* Only cleanup resources of tablesync workers */
1825  if (!OidIsValid(relid))
1826  continue;
1827 
1828  /*
1829  * Caller needs to ensure that relstate doesn't change underneath us.
1830  * See DropSubscription where we get the relstates.
1831  */
1832  if (rstate->state != SUBREL_STATE_SYNCDONE)
1833  {
1834  char syncslotname[NAMEDATALEN] = {0};
1835 
1836  ReplicationSlotNameForTablesync(subid, relid, syncslotname,
1837  sizeof(syncslotname));
1838  elog(WARNING, "could not drop tablesync replication slot \"%s\"",
1839  syncslotname);
1840  }
1841  }
1842 
1843  ereport(ERROR,
1844  (errcode(ERRCODE_CONNECTION_FAILURE),
1845  errmsg("could not connect to publisher when attempting to "
1846  "drop replication slot \"%s\": %s", slotname, err),
1847  /* translator: %s is an SQL ALTER command */
1848  errhint("Use %s to disassociate the subscription from the slot.",
1849  "ALTER SUBSCRIPTION ... SET (slot_name = NONE)")));
1850 }

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

Referenced by DropSubscription().