PostgreSQL Source Code  git master
subscriptioncmds.c File Reference
#include "postgres.h"
#include "access/htup_details.h"
#include "access/table.h"
#include "access/xact.h"
#include "catalog/catalog.h"
#include "catalog/dependency.h"
#include "catalog/indexing.h"
#include "catalog/namespace.h"
#include "catalog/objectaccess.h"
#include "catalog/objectaddress.h"
#include "catalog/pg_authid_d.h"
#include "catalog/pg_database_d.h"
#include "catalog/pg_subscription.h"
#include "catalog/pg_subscription_rel.h"
#include "catalog/pg_type.h"
#include "commands/dbcommands.h"
#include "commands/defrem.h"
#include "commands/event_trigger.h"
#include "commands/subscriptioncmds.h"
#include "executor/executor.h"
#include "miscadmin.h"
#include "nodes/makefuncs.h"
#include "pgstat.h"
#include "replication/logicallauncher.h"
#include "replication/logicalworker.h"
#include "replication/origin.h"
#include "replication/slot.h"
#include "replication/walreceiver.h"
#include "replication/walsender.h"
#include "replication/worker_internal.h"
#include "storage/lmgr.h"
#include "utils/acl.h"
#include "utils/builtins.h"
#include "utils/guc.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/pg_lsn.h"
#include "utils/syscache.h"
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_PASSWORD_REQUIRED   0x00000800
 
#define SUBOPT_RUN_AS_OWNER   0x00001000
 
#define SUBOPT_LSN   0x00002000
 
#define SUBOPT_ORIGIN   0x00004000
 
#define IsSet(val, bits)   (((val) & (bits)) == (bits))
 

Typedefs

typedef struct SubOpts SubOpts
 

Functions

static Listfetch_table_list (WalReceiverConn *wrconn, List *publications)
 
static void check_publications_origin (WalReceiverConn *wrconn, List *publications, bool copydata, char *origin, Oid *subrel_local_oids, int subrel_count, char *subname)
 
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)
 
char defGetStreamingMode (DefElem *def)
 

Macro Definition Documentation

◆ IsSet

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

Definition at line 76 of file subscriptioncmds.c.

◆ SUBOPT_BINARY

#define SUBOPT_BINARY   0x00000080

Definition at line 66 of file subscriptioncmds.c.

◆ SUBOPT_CONNECT

#define SUBOPT_CONNECT   0x00000001

Definition at line 59 of file subscriptioncmds.c.

◆ SUBOPT_COPY_DATA

#define SUBOPT_COPY_DATA   0x00000010

Definition at line 63 of file subscriptioncmds.c.

◆ SUBOPT_CREATE_SLOT

#define SUBOPT_CREATE_SLOT   0x00000004

Definition at line 61 of file subscriptioncmds.c.

◆ SUBOPT_DISABLE_ON_ERR

#define SUBOPT_DISABLE_ON_ERR   0x00000400

Definition at line 69 of file subscriptioncmds.c.

◆ SUBOPT_ENABLED

#define SUBOPT_ENABLED   0x00000002

Definition at line 60 of file subscriptioncmds.c.

◆ SUBOPT_LSN

#define SUBOPT_LSN   0x00002000

Definition at line 72 of file subscriptioncmds.c.

◆ SUBOPT_ORIGIN

#define SUBOPT_ORIGIN   0x00004000

Definition at line 73 of file subscriptioncmds.c.

◆ SUBOPT_PASSWORD_REQUIRED

#define SUBOPT_PASSWORD_REQUIRED   0x00000800

Definition at line 70 of file subscriptioncmds.c.

◆ SUBOPT_REFRESH

#define SUBOPT_REFRESH   0x00000040

Definition at line 65 of file subscriptioncmds.c.

◆ SUBOPT_RUN_AS_OWNER

#define SUBOPT_RUN_AS_OWNER   0x00001000

Definition at line 71 of file subscriptioncmds.c.

◆ SUBOPT_SLOT_NAME

#define SUBOPT_SLOT_NAME   0x00000008

Definition at line 62 of file subscriptioncmds.c.

◆ SUBOPT_STREAMING

#define SUBOPT_STREAMING   0x00000100

Definition at line 67 of file subscriptioncmds.c.

◆ SUBOPT_SYNCHRONOUS_COMMIT

#define SUBOPT_SYNCHRONOUS_COMMIT   0x00000020

Definition at line 64 of file subscriptioncmds.c.

◆ SUBOPT_TWOPHASE_COMMIT

#define SUBOPT_TWOPHASE_COMMIT   0x00000200

Definition at line 68 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 1071 of file subscriptioncmds.c.

1073 {
1074  Relation rel;
1075  ObjectAddress myself;
1076  bool nulls[Natts_pg_subscription];
1077  bool replaces[Natts_pg_subscription];
1078  Datum values[Natts_pg_subscription];
1079  HeapTuple tup;
1080  Oid subid;
1081  bool update_tuple = false;
1082  Subscription *sub;
1083  Form_pg_subscription form;
1084  bits32 supported_opts;
1085  SubOpts opts = {0};
1086 
1087  rel = table_open(SubscriptionRelationId, RowExclusiveLock);
1088 
1089  /* Fetch the existing tuple. */
1091  CStringGetDatum(stmt->subname));
1092 
1093  if (!HeapTupleIsValid(tup))
1094  ereport(ERROR,
1095  (errcode(ERRCODE_UNDEFINED_OBJECT),
1096  errmsg("subscription \"%s\" does not exist",
1097  stmt->subname)));
1098 
1099  form = (Form_pg_subscription) GETSTRUCT(tup);
1100  subid = form->oid;
1101 
1102  /* must be owner */
1103  if (!object_ownercheck(SubscriptionRelationId, subid, GetUserId()))
1105  stmt->subname);
1106 
1107  sub = GetSubscription(subid, false);
1108 
1109  /*
1110  * Don't allow non-superuser modification of a subscription with
1111  * password_required=false.
1112  */
1113  if (!sub->passwordrequired && !superuser())
1114  ereport(ERROR,
1115  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1116  errmsg("password_required=false is superuser-only"),
1117  errhint("Subscriptions with the password_required option set to false may only be created or modified by the superuser.")));
1118 
1119  /* Lock the subscription so nobody else can do anything with it. */
1120  LockSharedObject(SubscriptionRelationId, subid, 0, AccessExclusiveLock);
1121 
1122  /* Form a new tuple. */
1123  memset(values, 0, sizeof(values));
1124  memset(nulls, false, sizeof(nulls));
1125  memset(replaces, false, sizeof(replaces));
1126 
1127  switch (stmt->kind)
1128  {
1130  {
1131  supported_opts = (SUBOPT_SLOT_NAME |
1136 
1137  parse_subscription_options(pstate, stmt->options,
1138  supported_opts, &opts);
1139 
1140  if (IsSet(opts.specified_opts, SUBOPT_SLOT_NAME))
1141  {
1142  /*
1143  * The subscription must be disabled to allow slot_name as
1144  * 'none', otherwise, the apply worker will repeatedly try
1145  * to stream the data using that slot_name which neither
1146  * exists on the publisher nor the user will be allowed to
1147  * create it.
1148  */
1149  if (sub->enabled && !opts.slot_name)
1150  ereport(ERROR,
1151  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1152  errmsg("cannot set %s for enabled subscription",
1153  "slot_name = NONE")));
1154 
1155  if (opts.slot_name)
1156  values[Anum_pg_subscription_subslotname - 1] =
1158  else
1159  nulls[Anum_pg_subscription_subslotname - 1] = true;
1160  replaces[Anum_pg_subscription_subslotname - 1] = true;
1161  }
1162 
1163  if (opts.synchronous_commit)
1164  {
1165  values[Anum_pg_subscription_subsynccommit - 1] =
1166  CStringGetTextDatum(opts.synchronous_commit);
1167  replaces[Anum_pg_subscription_subsynccommit - 1] = true;
1168  }
1169 
1170  if (IsSet(opts.specified_opts, SUBOPT_BINARY))
1171  {
1172  values[Anum_pg_subscription_subbinary - 1] =
1173  BoolGetDatum(opts.binary);
1174  replaces[Anum_pg_subscription_subbinary - 1] = true;
1175  }
1176 
1177  if (IsSet(opts.specified_opts, SUBOPT_STREAMING))
1178  {
1179  values[Anum_pg_subscription_substream - 1] =
1180  CharGetDatum(opts.streaming);
1181  replaces[Anum_pg_subscription_substream - 1] = true;
1182  }
1183 
1184  if (IsSet(opts.specified_opts, SUBOPT_DISABLE_ON_ERR))
1185  {
1186  values[Anum_pg_subscription_subdisableonerr - 1]
1187  = BoolGetDatum(opts.disableonerr);
1188  replaces[Anum_pg_subscription_subdisableonerr - 1]
1189  = true;
1190  }
1191 
1192  if (IsSet(opts.specified_opts, SUBOPT_PASSWORD_REQUIRED))
1193  {
1194  /* Non-superuser may not disable password_required. */
1195  if (!opts.passwordrequired && !superuser())
1196  ereport(ERROR,
1197  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1198  errmsg("password_required=false is superuser-only"),
1199  errhint("Subscriptions with the password_required option set to false may only be created or modified by the superuser.")));
1200 
1201  values[Anum_pg_subscription_subpasswordrequired - 1]
1202  = BoolGetDatum(opts.passwordrequired);
1203  replaces[Anum_pg_subscription_subpasswordrequired - 1]
1204  = true;
1205  }
1206 
1207  if (IsSet(opts.specified_opts, SUBOPT_RUN_AS_OWNER))
1208  {
1209  values[Anum_pg_subscription_subrunasowner - 1] =
1210  BoolGetDatum(opts.runasowner);
1211  replaces[Anum_pg_subscription_subrunasowner - 1] = true;
1212  }
1213 
1214  if (IsSet(opts.specified_opts, SUBOPT_ORIGIN))
1215  {
1216  values[Anum_pg_subscription_suborigin - 1] =
1217  CStringGetTextDatum(opts.origin);
1218  replaces[Anum_pg_subscription_suborigin - 1] = true;
1219  }
1220 
1221  update_tuple = true;
1222  break;
1223  }
1224 
1226  {
1227  parse_subscription_options(pstate, stmt->options,
1228  SUBOPT_ENABLED, &opts);
1229  Assert(IsSet(opts.specified_opts, SUBOPT_ENABLED));
1230 
1231  if (!sub->slotname && opts.enabled)
1232  ereport(ERROR,
1233  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1234  errmsg("cannot enable subscription that does not have a slot name")));
1235 
1236  values[Anum_pg_subscription_subenabled - 1] =
1237  BoolGetDatum(opts.enabled);
1238  replaces[Anum_pg_subscription_subenabled - 1] = true;
1239 
1240  if (opts.enabled)
1242 
1243  update_tuple = true;
1244  break;
1245  }
1246 
1248  /* Load the library providing us libpq calls. */
1249  load_file("libpqwalreceiver", false);
1250  /* Check the connection info string. */
1251  walrcv_check_conninfo(stmt->conninfo,
1252  sub->passwordrequired && !superuser_arg(sub->owner));
1253 
1254  values[Anum_pg_subscription_subconninfo - 1] =
1255  CStringGetTextDatum(stmt->conninfo);
1256  replaces[Anum_pg_subscription_subconninfo - 1] = true;
1257  update_tuple = true;
1258  break;
1259 
1261  {
1262  supported_opts = SUBOPT_COPY_DATA | SUBOPT_REFRESH;
1263  parse_subscription_options(pstate, stmt->options,
1264  supported_opts, &opts);
1265 
1266  values[Anum_pg_subscription_subpublications - 1] =
1267  publicationListToArray(stmt->publication);
1268  replaces[Anum_pg_subscription_subpublications - 1] = true;
1269 
1270  update_tuple = true;
1271 
1272  /* Refresh if user asked us to. */
1273  if (opts.refresh)
1274  {
1275  if (!sub->enabled)
1276  ereport(ERROR,
1277  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1278  errmsg("ALTER SUBSCRIPTION with refresh is not allowed for disabled subscriptions"),
1279  errhint("Use ALTER SUBSCRIPTION ... SET PUBLICATION ... WITH (refresh = false).")));
1280 
1281  /*
1282  * See ALTER_SUBSCRIPTION_REFRESH for details why this is
1283  * not allowed.
1284  */
1285  if (sub->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED && opts.copy_data)
1286  ereport(ERROR,
1287  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1288  errmsg("ALTER SUBSCRIPTION with refresh and copy_data is not allowed when two_phase is enabled"),
1289  errhint("Use ALTER SUBSCRIPTION ... SET PUBLICATION with refresh = false, or with copy_data = false, or use DROP/CREATE SUBSCRIPTION.")));
1290 
1291  PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION with refresh");
1292 
1293  /* Make sure refresh sees the new list of publications. */
1294  sub->publications = stmt->publication;
1295 
1296  AlterSubscription_refresh(sub, opts.copy_data,
1297  stmt->publication);
1298  }
1299 
1300  break;
1301  }
1302 
1305  {
1306  List *publist;
1307  bool isadd = stmt->kind == ALTER_SUBSCRIPTION_ADD_PUBLICATION;
1308 
1309  supported_opts = SUBOPT_REFRESH | SUBOPT_COPY_DATA;
1310  parse_subscription_options(pstate, stmt->options,
1311  supported_opts, &opts);
1312 
1313  publist = merge_publications(sub->publications, stmt->publication, isadd, stmt->subname);
1314  values[Anum_pg_subscription_subpublications - 1] =
1315  publicationListToArray(publist);
1316  replaces[Anum_pg_subscription_subpublications - 1] = true;
1317 
1318  update_tuple = true;
1319 
1320  /* Refresh if user asked us to. */
1321  if (opts.refresh)
1322  {
1323  /* We only need to validate user specified publications. */
1324  List *validate_publications = (isadd) ? stmt->publication : NULL;
1325 
1326  if (!sub->enabled)
1327  ereport(ERROR,
1328  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1329  errmsg("ALTER SUBSCRIPTION with refresh is not allowed for disabled subscriptions"),
1330  /* translator: %s is an SQL ALTER command */
1331  errhint("Use %s instead.",
1332  isadd ?
1333  "ALTER SUBSCRIPTION ... ADD PUBLICATION ... WITH (refresh = false)" :
1334  "ALTER SUBSCRIPTION ... DROP PUBLICATION ... WITH (refresh = false)")));
1335 
1336  /*
1337  * See ALTER_SUBSCRIPTION_REFRESH for details why this is
1338  * not allowed.
1339  */
1340  if (sub->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED && opts.copy_data)
1341  ereport(ERROR,
1342  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1343  errmsg("ALTER SUBSCRIPTION with refresh and copy_data is not allowed when two_phase is enabled"),
1344  /* translator: %s is an SQL ALTER command */
1345  errhint("Use %s with refresh = false, or with copy_data = false, or use DROP/CREATE SUBSCRIPTION.",
1346  isadd ?
1347  "ALTER SUBSCRIPTION ... ADD PUBLICATION" :
1348  "ALTER SUBSCRIPTION ... DROP PUBLICATION")));
1349 
1350  PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION with refresh");
1351 
1352  /* Refresh the new list of publications. */
1353  sub->publications = publist;
1354 
1355  AlterSubscription_refresh(sub, opts.copy_data,
1356  validate_publications);
1357  }
1358 
1359  break;
1360  }
1361 
1363  {
1364  if (!sub->enabled)
1365  ereport(ERROR,
1366  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1367  errmsg("ALTER SUBSCRIPTION ... REFRESH is not allowed for disabled subscriptions")));
1368 
1369  parse_subscription_options(pstate, stmt->options,
1371 
1372  /*
1373  * The subscription option "two_phase" requires that
1374  * replication has passed the initial table synchronization
1375  * phase before the two_phase becomes properly enabled.
1376  *
1377  * But, having reached this two-phase commit "enabled" state
1378  * we must not allow any subsequent table initialization to
1379  * occur. So the ALTER SUBSCRIPTION ... REFRESH is disallowed
1380  * when the user had requested two_phase = on mode.
1381  *
1382  * The exception to this restriction is when copy_data =
1383  * false, because when copy_data is false the tablesync will
1384  * start already in READY state and will exit directly without
1385  * doing anything.
1386  *
1387  * For more details see comments atop worker.c.
1388  */
1389  if (sub->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED && opts.copy_data)
1390  ereport(ERROR,
1391  (errcode(ERRCODE_SYNTAX_ERROR),
1392  errmsg("ALTER SUBSCRIPTION ... REFRESH with copy_data is not allowed when two_phase is enabled"),
1393  errhint("Use ALTER SUBSCRIPTION ... REFRESH with copy_data = false, or use DROP/CREATE SUBSCRIPTION.")));
1394 
1395  PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION ... REFRESH");
1396 
1397  AlterSubscription_refresh(sub, opts.copy_data, NULL);
1398 
1399  break;
1400  }
1401 
1403  {
1404  parse_subscription_options(pstate, stmt->options, SUBOPT_LSN, &opts);
1405 
1406  /* ALTER SUBSCRIPTION ... SKIP supports only LSN option */
1407  Assert(IsSet(opts.specified_opts, SUBOPT_LSN));
1408 
1409  /*
1410  * If the user sets subskiplsn, we do a sanity check to make
1411  * sure that the specified LSN is a probable value.
1412  */
1413  if (!XLogRecPtrIsInvalid(opts.lsn))
1414  {
1415  RepOriginId originid;
1416  char originname[NAMEDATALEN];
1417  XLogRecPtr remote_lsn;
1418 
1420  originname, sizeof(originname));
1421  originid = replorigin_by_name(originname, false);
1422  remote_lsn = replorigin_get_progress(originid, false);
1423 
1424  /* Check the given LSN is at least a future LSN */
1425  if (!XLogRecPtrIsInvalid(remote_lsn) && opts.lsn < remote_lsn)
1426  ereport(ERROR,
1427  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1428  errmsg("skip WAL location (LSN %X/%X) must be greater than origin LSN %X/%X",
1429  LSN_FORMAT_ARGS(opts.lsn),
1430  LSN_FORMAT_ARGS(remote_lsn))));
1431  }
1432 
1433  values[Anum_pg_subscription_subskiplsn - 1] = LSNGetDatum(opts.lsn);
1434  replaces[Anum_pg_subscription_subskiplsn - 1] = true;
1435 
1436  update_tuple = true;
1437  break;
1438  }
1439 
1440  default:
1441  elog(ERROR, "unrecognized ALTER SUBSCRIPTION kind %d",
1442  stmt->kind);
1443  }
1444 
1445  /* Update the catalog if needed. */
1446  if (update_tuple)
1447  {
1448  tup = heap_modify_tuple(tup, RelationGetDescr(rel), values, nulls,
1449  replaces);
1450 
1451  CatalogTupleUpdate(rel, &tup->t_self, tup);
1452 
1453  heap_freetuple(tup);
1454  }
1455 
1457 
1458  ObjectAddressSet(myself, SubscriptionRelationId, subid);
1459 
1460  InvokeObjectPostAlterHook(SubscriptionRelationId, subid, 0);
1461 
1462  /* Wake up related replication workers to handle this change quickly. */
1464 
1465  return myself;
1466 }
@ ACLCHECK_NOT_OWNER
Definition: acl.h:184
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:2669
bool object_ownercheck(Oid classid, Oid objectid, Oid roleid)
Definition: aclchk.c:3961
void LogicalRepWorkersWakeupAtCommit(Oid subid)
Definition: worker.c:4989
void ReplicationOriginNameForLogicalRep(Oid suboid, Oid relid, char *originname, Size szoriginname)
Definition: worker.c:446
static Datum values[MAXATTR]
Definition: bootstrap.c:156
#define CStringGetTextDatum(s)
Definition: builtins.h:94
uint32 bits32
Definition: c.h:504
void load_file(const char *filename, bool restricted)
Definition: dfmgr.c:144
int errhint(const char *fmt,...)
Definition: elog.c:1316
int errcode(int sqlerrcode)
Definition: elog.c:858
int errmsg(const char *fmt,...)
Definition: elog.c:1069
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:642
Oid MyDatabaseId
Definition: globals.c:89
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:1201
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1426
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:653
#define stmt
Definition: indent_codes.h:59
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:313
if(TABLE==NULL||TABLE_index==NULL)
Definition: isn.c:77
void ApplyLauncherWakeupAtCommit(void)
Definition: launcher.c:1104
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:509
Datum namein(PG_FUNCTION_ARGS)
Definition: name.c:48
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:197
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
RepOriginId replorigin_by_name(const char *roname, bool missing_ok)
Definition: origin.c:221
XLogRecPtr replorigin_get_progress(RepOriginId node, bool flush)
Definition: origin.c:1014
@ ALTER_SUBSCRIPTION_ENABLED
Definition: parsenodes.h:4080
@ ALTER_SUBSCRIPTION_DROP_PUBLICATION
Definition: parsenodes.h:4078
@ ALTER_SUBSCRIPTION_SET_PUBLICATION
Definition: parsenodes.h:4076
@ ALTER_SUBSCRIPTION_REFRESH
Definition: parsenodes.h:4079
@ ALTER_SUBSCRIPTION_SKIP
Definition: parsenodes.h:4081
@ ALTER_SUBSCRIPTION_OPTIONS
Definition: parsenodes.h:4074
@ ALTER_SUBSCRIPTION_CONNECTION
Definition: parsenodes.h:4075
@ ALTER_SUBSCRIPTION_ADD_PUBLICATION
Definition: parsenodes.h:4077
@ OBJECT_SUBSCRIPTION
Definition: parsenodes.h:2158
static AmcheckOptions opts
Definition: pg_amcheck.c:110
#define NAMEDATALEN
static Datum LSNGetDatum(XLogRecPtr X)
Definition: pg_lsn.h:28
Subscription * GetSubscription(Oid subid, bool missing_ok)
#define LOGICALREP_TWOPHASE_STATE_ENABLED
FormData_pg_subscription * Form_pg_subscription
uintptr_t Datum
Definition: postgres.h:64
static Datum BoolGetDatum(bool X)
Definition: postgres.h:102
static Datum CStringGetDatum(const char *X)
Definition: postgres.h:350
static Datum CharGetDatum(char X)
Definition: postgres.h:122
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
#define RelationGetDescr(relation)
Definition: rel.h:530
ItemPointerData t_self
Definition: htup.h:65
Definition: pg_list.h:54
#define SUBOPT_STREAMING
#define SUBOPT_PASSWORD_REQUIRED
#define SUBOPT_SYNCHRONOUS_COMMIT
#define SUBOPT_ENABLED
#define SUBOPT_ORIGIN
static Datum publicationListToArray(List *publist)
static void parse_subscription_options(ParseState *pstate, List *stmt_options, bits32 supported_opts, SubOpts *opts)
#define SUBOPT_RUN_AS_OWNER
#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_arg(Oid roleid)
Definition: superuser.c:56
bool superuser(void)
Definition: superuser.c:46
#define SearchSysCacheCopy2(cacheId, key1, key2)
Definition: syscache.h:184
@ SUBSCRIPTIONNAME
Definition: syscache.h:98
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:40
#define walrcv_check_conninfo(conninfo, must_use_password)
Definition: walreceiver.h:412
void PreventInTransactionBlock(bool isTopLevel, const char *stmtType)
Definition: xact.c:3481
#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(), CharGetDatum(), CStringGetDatum(), CStringGetTextDatum, DirectFunctionCall1, elog(), Subscription::enabled, ereport, errcode(), errhint(), errmsg(), ERROR, GETSTRUCT, GetSubscription(), GetUserId(), heap_freetuple(), heap_modify_tuple(), HeapTupleIsValid, if(), InvalidOid, InvokeObjectPostAlterHook, IsSet, load_file(), LockSharedObject(), LOGICALREP_TWOPHASE_STATE_ENABLED, LogicalRepWorkersWakeupAtCommit(), LSN_FORMAT_ARGS, LSNGetDatum(), merge_publications(), MyDatabaseId, NAMEDATALEN, namein(), object_ownercheck(), OBJECT_SUBSCRIPTION, ObjectAddressSet, opts, Subscription::owner, parse_subscription_options(), Subscription::passwordrequired, PreventInTransactionBlock(), publicationListToArray(), Subscription::publications, RelationGetDescr, ReplicationOriginNameForLogicalRep(), replorigin_by_name(), replorigin_get_progress(), RowExclusiveLock, SearchSysCacheCopy2, Subscription::slotname, stmt, SUBOPT_BINARY, SUBOPT_COPY_DATA, SUBOPT_DISABLE_ON_ERR, SUBOPT_ENABLED, SUBOPT_LSN, SUBOPT_ORIGIN, SUBOPT_PASSWORD_REQUIRED, SUBOPT_REFRESH, SUBOPT_RUN_AS_OWNER, SUBOPT_SLOT_NAME, SUBOPT_STREAMING, SUBOPT_SYNCHRONOUS_COMMIT, SUBSCRIPTIONNAME, superuser(), superuser_arg(), 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 846 of file subscriptioncmds.c.

848 {
849  char *err;
850  List *pubrel_names;
851  List *subrel_states;
852  Oid *subrel_local_oids;
853  Oid *pubrel_local_oids;
854  ListCell *lc;
855  int off;
856  int remove_rel_len;
857  int subrel_count;
858  Relation rel = NULL;
859  typedef struct SubRemoveRels
860  {
861  Oid relid;
862  char state;
863  } SubRemoveRels;
864  SubRemoveRels *sub_remove_rels;
866  bool must_use_password;
867 
868  /* Load the library providing us libpq calls. */
869  load_file("libpqwalreceiver", false);
870 
871  /* Try to connect to the publisher. */
872  must_use_password = !superuser_arg(sub->owner) && sub->passwordrequired;
873  wrconn = walrcv_connect(sub->conninfo, true, must_use_password,
874  sub->name, &err);
875  if (!wrconn)
876  ereport(ERROR,
877  (errcode(ERRCODE_CONNECTION_FAILURE),
878  errmsg("could not connect to the publisher: %s", err)));
879 
880  PG_TRY();
881  {
882  if (validate_publications)
883  check_publications(wrconn, validate_publications);
884 
885  /* Get the table list from publisher. */
886  pubrel_names = fetch_table_list(wrconn, sub->publications);
887 
888  /* Get local table list. */
889  subrel_states = GetSubscriptionRelations(sub->oid, false);
890  subrel_count = list_length(subrel_states);
891 
892  /*
893  * Build qsorted array of local table oids for faster lookup. This can
894  * potentially contain all tables in the database so speed of lookup
895  * is important.
896  */
897  subrel_local_oids = palloc(subrel_count * sizeof(Oid));
898  off = 0;
899  foreach(lc, subrel_states)
900  {
902 
903  subrel_local_oids[off++] = relstate->relid;
904  }
905  qsort(subrel_local_oids, subrel_count,
906  sizeof(Oid), oid_cmp);
907 
909  sub->origin, subrel_local_oids,
910  subrel_count, sub->name);
911 
912  /*
913  * Rels that we want to remove from subscription and drop any slots
914  * and origins corresponding to them.
915  */
916  sub_remove_rels = palloc(subrel_count * sizeof(SubRemoveRels));
917 
918  /*
919  * Walk over the remote tables and try to match them to locally known
920  * tables. If the table is not known locally create a new state for
921  * it.
922  *
923  * Also builds array of local oids of remote tables for the next step.
924  */
925  off = 0;
926  pubrel_local_oids = palloc(list_length(pubrel_names) * sizeof(Oid));
927 
928  foreach(lc, pubrel_names)
929  {
930  RangeVar *rv = (RangeVar *) lfirst(lc);
931  Oid relid;
932 
933  relid = RangeVarGetRelid(rv, AccessShareLock, false);
934 
935  /* Check for supported relkind. */
937  rv->schemaname, rv->relname);
938 
939  pubrel_local_oids[off++] = relid;
940 
941  if (!bsearch(&relid, subrel_local_oids,
942  subrel_count, sizeof(Oid), oid_cmp))
943  {
944  AddSubscriptionRelState(sub->oid, relid,
945  copy_data ? SUBREL_STATE_INIT : SUBREL_STATE_READY,
947  ereport(DEBUG1,
948  (errmsg_internal("table \"%s.%s\" added to subscription \"%s\"",
949  rv->schemaname, rv->relname, sub->name)));
950  }
951  }
952 
953  /*
954  * Next remove state for tables we should not care about anymore using
955  * the data we collected above
956  */
957  qsort(pubrel_local_oids, list_length(pubrel_names),
958  sizeof(Oid), oid_cmp);
959 
960  remove_rel_len = 0;
961  for (off = 0; off < subrel_count; off++)
962  {
963  Oid relid = subrel_local_oids[off];
964 
965  if (!bsearch(&relid, pubrel_local_oids,
966  list_length(pubrel_names), sizeof(Oid), oid_cmp))
967  {
968  char state;
969  XLogRecPtr statelsn;
970 
971  /*
972  * Lock pg_subscription_rel with AccessExclusiveLock to
973  * prevent any race conditions with the apply worker
974  * re-launching workers at the same time this code is trying
975  * to remove those tables.
976  *
977  * Even if new worker for this particular rel is restarted it
978  * won't be able to make any progress as we hold exclusive
979  * lock on pg_subscription_rel till the transaction end. It
980  * will simply exit as there is no corresponding rel entry.
981  *
982  * This locking also ensures that the state of rels won't
983  * change till we are done with this refresh operation.
984  */
985  if (!rel)
986  rel = table_open(SubscriptionRelRelationId, AccessExclusiveLock);
987 
988  /* Last known rel state. */
989  state = GetSubscriptionRelState(sub->oid, relid, &statelsn);
990 
991  sub_remove_rels[remove_rel_len].relid = relid;
992  sub_remove_rels[remove_rel_len++].state = state;
993 
994  RemoveSubscriptionRel(sub->oid, relid);
995 
996  logicalrep_worker_stop(sub->oid, relid);
997 
998  /*
999  * For READY state, we would have already dropped the
1000  * tablesync origin.
1001  */
1002  if (state != SUBREL_STATE_READY)
1003  {
1004  char originname[NAMEDATALEN];
1005 
1006  /*
1007  * Drop the tablesync's origin tracking if exists.
1008  *
1009  * It is possible that the origin is not yet created for
1010  * tablesync worker, this can happen for the states before
1011  * SUBREL_STATE_FINISHEDCOPY. The tablesync worker or
1012  * apply worker can also concurrently try to drop the
1013  * origin and by this time the origin might be already
1014  * removed. For these reasons, passing missing_ok = true.
1015  */
1016  ReplicationOriginNameForLogicalRep(sub->oid, relid, originname,
1017  sizeof(originname));
1018  replorigin_drop_by_name(originname, true, false);
1019  }
1020 
1021  ereport(DEBUG1,
1022  (errmsg_internal("table \"%s.%s\" removed from subscription \"%s\"",
1024  get_rel_name(relid),
1025  sub->name)));
1026  }
1027  }
1028 
1029  /*
1030  * Drop the tablesync slots associated with removed tables. This has
1031  * to be at the end because otherwise if there is an error while doing
1032  * the database operations we won't be able to rollback dropped slots.
1033  */
1034  for (off = 0; off < remove_rel_len; off++)
1035  {
1036  if (sub_remove_rels[off].state != SUBREL_STATE_READY &&
1037  sub_remove_rels[off].state != SUBREL_STATE_SYNCDONE)
1038  {
1039  char syncslotname[NAMEDATALEN] = {0};
1040 
1041  /*
1042  * For READY/SYNCDONE states we know the tablesync slot has
1043  * already been dropped by the tablesync worker.
1044  *
1045  * For other states, there is no certainty, maybe the slot
1046  * does not exist yet. Also, if we fail after removing some of
1047  * the slots, next time, it will again try to drop already
1048  * dropped slots and fail. For these reasons, we allow
1049  * missing_ok = true for the drop.
1050  */
1051  ReplicationSlotNameForTablesync(sub->oid, sub_remove_rels[off].relid,
1052  syncslotname, sizeof(syncslotname));
1053  ReplicationSlotDropAtPubNode(wrconn, syncslotname, true);
1054  }
1055  }
1056  }
1057  PG_FINALLY();
1058  {
1060  }
1061  PG_END_TRY();
1062 
1063  if (rel)
1064  table_close(rel, NoLock);
1065 }
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1156
#define PG_TRY(...)
Definition: elog.h:370
#define PG_END_TRY(...)
Definition: elog.h:395
#define DEBUG1
Definition: elog.h:30
#define PG_FINALLY(...)
Definition: elog.h:387
void err(int eval, const char *fmt,...)
Definition: err.c:43
void CheckSubscriptionRelkind(char relkind, const char *nspname, const char *relname)
void logicalrep_worker_stop(Oid subid, Oid relid)
Definition: launcher.c:615
#define NoLock
Definition: lockdefs.h:34
#define AccessShareLock
Definition: lockdefs.h:36
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3348
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:2007
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1956
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1932
void * palloc(Size size)
Definition: mcxt.c:1226
#define RangeVarGetRelid(relation, lockmode, missing_ok)
Definition: namespace.h:79
int oid_cmp(const void *p1, const void *p2)
Definition: oid.c:257
void replorigin_drop_by_name(const char *name, bool missing_ok, bool nowait)
Definition: origin.c:411
#define lfirst(lc)
Definition: pg_list.h:172
static int list_length(const List *l)
Definition: pg_list.h:152
void RemoveSubscriptionRel(Oid subid, Oid relid)
List * GetSubscriptionRelations(Oid subid, bool not_ready)
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:445
char * relname
Definition: primnodes.h:74
char * schemaname
Definition: primnodes.h:71
Definition: regguts.h:323
static void check_publications(WalReceiverConn *wrconn, List *publications)
static void check_publications_origin(WalReceiverConn *wrconn, List *publications, bool copydata, char *origin, Oid *subrel_local_oids, int subrel_count, char *subname)
void ReplicationSlotDropAtPubNode(WalReceiverConn *wrconn, char *slotname, bool missing_ok)
static List * fetch_table_list(WalReceiverConn *wrconn, List *publications)
void ReplicationSlotNameForTablesync(Oid suboid, Oid relid, char *syncslotname, Size szslot)
Definition: tablesync.c:1242
static WalReceiverConn * wrconn
Definition: walreceiver.c:95
#define walrcv_connect(conninfo, logical, must_use_password, appname, err)
Definition: walreceiver.h:410
#define walrcv_disconnect(conn)
Definition: walreceiver.h:438
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28

References AccessExclusiveLock, AccessShareLock, AddSubscriptionRelState(), check_publications(), check_publications_origin(), CheckSubscriptionRelkind(), Subscription::conninfo, DEBUG1, ereport, err(), 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(), Subscription::origin, Subscription::owner, palloc(), Subscription::passwordrequired, PG_END_TRY, PG_FINALLY, PG_TRY, Subscription::publications, qsort, RangeVarGetRelid, SubscriptionRelState::relid, RangeVar::relname, RemoveSubscriptionRel(), ReplicationOriginNameForLogicalRep(), ReplicationSlotDropAtPubNode(), ReplicationSlotNameForTablesync(), replorigin_drop_by_name(), RangeVar::schemaname, superuser_arg(), table_close(), table_open(), walrcv_connect, walrcv_disconnect, and wrconn.

Referenced by AlterSubscription().

◆ AlterSubscriptionOwner()

ObjectAddress AlterSubscriptionOwner ( const char *  name,
Oid  newOwnerId 
)

Definition at line 1876 of file subscriptioncmds.c.

1877 {
1878  Oid subid;
1879  HeapTuple tup;
1880  Relation rel;
1881  ObjectAddress address;
1882  Form_pg_subscription form;
1883 
1884  rel = table_open(SubscriptionRelationId, RowExclusiveLock);
1885 
1888 
1889  if (!HeapTupleIsValid(tup))
1890  ereport(ERROR,
1891  (errcode(ERRCODE_UNDEFINED_OBJECT),
1892  errmsg("subscription \"%s\" does not exist", name)));
1893 
1894  form = (Form_pg_subscription) GETSTRUCT(tup);
1895  subid = form->oid;
1896 
1897  AlterSubscriptionOwner_internal(rel, tup, newOwnerId);
1898 
1899  ObjectAddressSet(address, SubscriptionRelationId, subid);
1900 
1901  heap_freetuple(tup);
1902 
1904 
1905  return address;
1906 }
static void AlterSubscriptionOwner_internal(Relation rel, HeapTuple tup, Oid newOwnerId)
const char * name

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 1816 of file subscriptioncmds.c.

1817 {
1818  Form_pg_subscription form;
1819  AclResult aclresult;
1820 
1821  form = (Form_pg_subscription) GETSTRUCT(tup);
1822 
1823  if (form->subowner == newOwnerId)
1824  return;
1825 
1826  if (!object_ownercheck(SubscriptionRelationId, form->oid, GetUserId()))
1828  NameStr(form->subname));
1829 
1830  /*
1831  * Don't allow non-superuser modification of a subscription with
1832  * password_required=false.
1833  */
1834  if (!form->subpasswordrequired && !superuser())
1835  ereport(ERROR,
1836  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1837  errmsg("password_required=false is superuser-only"),
1838  errhint("Subscriptions with the password_required option set to false may only be created or modified by the superuser.")));
1839 
1840  /* Must be able to become new owner */
1841  check_can_set_role(GetUserId(), newOwnerId);
1842 
1843  /*
1844  * current owner must have CREATE on database
1845  *
1846  * This is consistent with how ALTER SCHEMA ... OWNER TO works, but some
1847  * other object types behave differently (e.g. you can't give a table to a
1848  * user who lacks CREATE privileges on a schema).
1849  */
1850  aclresult = object_aclcheck(DatabaseRelationId, MyDatabaseId,
1851  GetUserId(), ACL_CREATE);
1852  if (aclresult != ACLCHECK_OK)
1853  aclcheck_error(aclresult, OBJECT_DATABASE,
1855 
1856  form->subowner = newOwnerId;
1857  CatalogTupleUpdate(rel, &tup->t_self, tup);
1858 
1859  /* Update owner dependency reference */
1860  changeDependencyOnOwner(SubscriptionRelationId,
1861  form->oid,
1862  newOwnerId);
1863 
1864  InvokeObjectPostAlterHook(SubscriptionRelationId,
1865  form->oid, 0);
1866 
1867  /* Wake up related background processes to handle this change quickly. */
1870 }
void check_can_set_role(Oid member, Oid role)
Definition: acl.c:5018
AclResult
Definition: acl.h:181
@ ACLCHECK_OK
Definition: acl.h:182
AclResult object_aclcheck(Oid classid, Oid objectid, Oid roleid, AclMode mode)
Definition: aclchk.c:3760
#define NameStr(name)
Definition: c.h:735
char * get_database_name(Oid dbid)
Definition: dbcommands.c:3084
@ OBJECT_DATABASE
Definition: parsenodes.h:2129
#define ACL_CREATE
Definition: parsenodes.h:92
void changeDependencyOnOwner(Oid classId, Oid objectId, Oid newOwnerId)
Definition: pg_shdepend.c:313

References ACL_CREATE, aclcheck_error(), ACLCHECK_NOT_OWNER, ACLCHECK_OK, ApplyLauncherWakeupAtCommit(), CatalogTupleUpdate(), changeDependencyOnOwner(), check_can_set_role(), ereport, errcode(), errhint(), errmsg(), ERROR, get_database_name(), GETSTRUCT, GetUserId(), InvokeObjectPostAlterHook, LogicalRepWorkersWakeupAtCommit(), MyDatabaseId, NameStr, object_aclcheck(), OBJECT_DATABASE, object_ownercheck(), OBJECT_SUBSCRIPTION, superuser(), and HeapTupleData::t_self.

Referenced by AlterSubscriptionOwner(), and AlterSubscriptionOwner_oid().

◆ AlterSubscriptionOwner_oid()

void AlterSubscriptionOwner_oid ( Oid  subid,
Oid  newOwnerId 
)

Definition at line 1912 of file subscriptioncmds.c.

1913 {
1914  HeapTuple tup;
1915  Relation rel;
1916 
1917  rel = table_open(SubscriptionRelationId, RowExclusiveLock);
1918 
1920 
1921  if (!HeapTupleIsValid(tup))
1922  ereport(ERROR,
1923  (errcode(ERRCODE_UNDEFINED_OBJECT),
1924  errmsg("subscription with OID %u does not exist", subid)));
1925 
1926  AlterSubscriptionOwner_internal(rel, tup, newOwnerId);
1927 
1928  heap_freetuple(tup);
1929 
1931 }
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:252
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:182
@ 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 2206 of file subscriptioncmds.c.

2207 {
2208  ListCell *cell;
2209  int j = 0;
2210 
2211  foreach(cell, publist)
2212  {
2213  char *name = strVal(lfirst(cell));
2214  ListCell *pcell;
2215 
2216  foreach(pcell, publist)
2217  {
2218  char *pname = strVal(lfirst(pcell));
2219 
2220  if (pcell == cell)
2221  break;
2222 
2223  if (strcmp(name, pname) == 0)
2224  ereport(ERROR,
2226  errmsg("publication name \"%s\" used more than once",
2227  pname)));
2228  }
2229 
2230  if (datums)
2231  datums[j++] = CStringGetTextDatum(name);
2232  }
2233 }
int j
Definition: isn.c:74
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:32
#define strVal(v)
Definition: value.h:82

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 473 of file subscriptioncmds.c.

474 {
476  StringInfo cmd;
477  TupleTableSlot *slot;
478  List *publicationsCopy = NIL;
479  Oid tableRow[1] = {TEXTOID};
480 
481  cmd = makeStringInfo();
482  appendStringInfoString(cmd, "SELECT t.pubname FROM\n"
483  " pg_catalog.pg_publication t WHERE\n"
484  " t.pubname IN (");
485  get_publications_str(publications, cmd, true);
486  appendStringInfoChar(cmd, ')');
487 
488  res = walrcv_exec(wrconn, cmd->data, 1, tableRow);
489  pfree(cmd->data);
490  pfree(cmd);
491 
492  if (res->status != WALRCV_OK_TUPLES)
493  ereport(ERROR,
494  errmsg("could not receive list of publications from the publisher: %s",
495  res->err));
496 
497  publicationsCopy = list_copy(publications);
498 
499  /* Process publication(s). */
500  slot = MakeSingleTupleTableSlot(res->tupledesc, &TTSOpsMinimalTuple);
501  while (tuplestore_gettupleslot(res->tuplestore, true, false, slot))
502  {
503  char *pubname;
504  bool isnull;
505 
506  pubname = TextDatumGetCString(slot_getattr(slot, 1, &isnull));
507  Assert(!isnull);
508 
509  /* Delete the publication present in publisher from the list. */
510  publicationsCopy = list_delete(publicationsCopy, makeString(pubname));
511  ExecClearTuple(slot);
512  }
513 
515 
517 
518  if (list_length(publicationsCopy))
519  {
520  /* Prepare the list of non-existent publication(s) for error message. */
521  StringInfo pubnames = makeStringInfo();
522 
523  get_publications_str(publicationsCopy, pubnames, false);
525  errcode(ERRCODE_UNDEFINED_OBJECT),
526  errmsg_plural("publication %s does not exist on the publisher",
527  "publications %s do not exist on the publisher",
528  list_length(publicationsCopy),
529  pubnames->data));
530  }
531 }
#define TextDatumGetCString(d)
Definition: builtins.h:95
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:1179
#define WARNING
Definition: elog.h:36
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1255
const TupleTableSlotOps TTSOpsMinimalTuple
Definition: execTuples.c:85
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1239
List * list_copy(const List *oldlist)
Definition: list.c:1572
List * list_delete(List *list, void *datum)
Definition: list.c:852
void pfree(void *pointer)
Definition: mcxt.c:1456
#define NIL
Definition: pg_list.h:68
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:432
static Datum slot_getattr(TupleTableSlot *slot, int attnum, bool *isnull)
Definition: tuptable.h:388
String * makeString(char *str)
Definition: value.c:63
@ WALRCV_OK_TUPLES
Definition: walreceiver.h:207
static void walrcv_clear_result(WalRcvExecResult *walres)
Definition: walreceiver.h:442
#define walrcv_exec(conn, exec, nRetTypes, retTypes)
Definition: walreceiver.h:436

References appendStringInfoChar(), appendStringInfoString(), Assert(), StringInfoData::data, ereport, errcode(), errmsg(), 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().

◆ check_publications_origin()

static void check_publications_origin ( WalReceiverConn wrconn,
List publications,
bool  copydata,
char *  origin,
Oid subrel_local_oids,
int  subrel_count,
char *  subname 
)
static

Definition at line 1948 of file subscriptioncmds.c.

1951 {
1953  StringInfoData cmd;
1954  TupleTableSlot *slot;
1955  Oid tableRow[1] = {TEXTOID};
1956  List *publist = NIL;
1957  int i;
1958 
1959  if (!copydata || !origin ||
1960  (pg_strcasecmp(origin, LOGICALREP_ORIGIN_NONE) != 0))
1961  return;
1962 
1963  initStringInfo(&cmd);
1965  "SELECT DISTINCT P.pubname AS pubname\n"
1966  "FROM pg_publication P,\n"
1967  " LATERAL pg_get_publication_tables(P.pubname) GPT\n"
1968  " JOIN pg_subscription_rel PS ON (GPT.relid = PS.srrelid),\n"
1969  " pg_class C JOIN pg_namespace N ON (N.oid = C.relnamespace)\n"
1970  "WHERE C.oid = GPT.relid AND P.pubname IN (");
1971  get_publications_str(publications, &cmd, true);
1972  appendStringInfoString(&cmd, ")\n");
1973 
1974  /*
1975  * In case of ALTER SUBSCRIPTION ... REFRESH, subrel_local_oids contains
1976  * the list of relation oids that are already present on the subscriber.
1977  * This check should be skipped for these tables.
1978  */
1979  for (i = 0; i < subrel_count; i++)
1980  {
1981  Oid relid = subrel_local_oids[i];
1982  char *schemaname = get_namespace_name(get_rel_namespace(relid));
1983  char *tablename = get_rel_name(relid);
1984 
1985  appendStringInfo(&cmd, "AND NOT (N.nspname = '%s' AND C.relname = '%s')\n",
1986  schemaname, tablename);
1987  }
1988 
1989  res = walrcv_exec(wrconn, cmd.data, 1, tableRow);
1990  pfree(cmd.data);
1991 
1992  if (res->status != WALRCV_OK_TUPLES)
1993  ereport(ERROR,
1994  (errcode(ERRCODE_CONNECTION_FAILURE),
1995  errmsg("could not receive list of replicated tables from the publisher: %s",
1996  res->err)));
1997 
1998  /* Process tables. */
1999  slot = MakeSingleTupleTableSlot(res->tupledesc, &TTSOpsMinimalTuple);
2000  while (tuplestore_gettupleslot(res->tuplestore, true, false, slot))
2001  {
2002  char *pubname;
2003  bool isnull;
2004 
2005  pubname = TextDatumGetCString(slot_getattr(slot, 1, &isnull));
2006  Assert(!isnull);
2007 
2008  ExecClearTuple(slot);
2009  publist = list_append_unique(publist, makeString(pubname));
2010  }
2011 
2012  /*
2013  * Log a warning if the publisher has subscribed to the same table from
2014  * some other publisher. We cannot know the origin of data during the
2015  * initial sync. Data origins can be found only from the WAL by looking at
2016  * the origin id.
2017  *
2018  * XXX: For simplicity, we don't check whether the table has any data or
2019  * not. If the table doesn't have any data then we don't need to
2020  * distinguish between data having origin and data not having origin so we
2021  * can avoid logging a warning in that case.
2022  */
2023  if (publist)
2024  {
2025  StringInfo pubnames = makeStringInfo();
2026 
2027  /* Prepare the list of publication(s) for warning message. */
2028  get_publications_str(publist, pubnames, false);
2029  ereport(WARNING,
2030  errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2031  errmsg("subscription \"%s\" requested copy_data with origin = NONE but might copy data that had a different origin",
2032  subname),
2033  errdetail_plural("The subscription being created subscribes to a publication (%s) that contains tables that are written to by other subscriptions.",
2034  "The subscription being created subscribes to publications (%s) that contain tables that are written to by other subscriptions.",
2035  list_length(publist), pubnames->data),
2036  errhint("Verify that initial data copied from the publisher tables did not come from other origins."));
2037  }
2038 
2040 
2042 }
int errdetail_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:1294
int i
Definition: isn.c:73
List * list_append_unique(List *list, void *datum)
Definition: list.c:1342
#define LOGICALREP_ORIGIN_NONE
NameData subname
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59

References appendStringInfo(), appendStringInfoString(), Assert(), StringInfoData::data, ereport, errcode(), errdetail_plural(), errhint(), errmsg(), ERROR, ExecClearTuple(), ExecDropSingleTupleTableSlot(), get_namespace_name(), get_publications_str(), get_rel_name(), get_rel_namespace(), i, initStringInfo(), list_append_unique(), list_length(), LOGICALREP_ORIGIN_NONE, MakeSingleTupleTableSlot(), makeString(), makeStringInfo(), NIL, pfree(), pg_strcasecmp(), res, slot_getattr(), subname, 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 567 of file subscriptioncmds.c.

569 {
570  Relation rel;
571  ObjectAddress myself;
572  Oid subid;
573  bool nulls[Natts_pg_subscription];
574  Datum values[Natts_pg_subscription];
575  Oid owner = GetUserId();
576  HeapTuple tup;
577  char *conninfo;
578  char originname[NAMEDATALEN];
579  List *publications;
580  bits32 supported_opts;
581  SubOpts opts = {0};
582  AclResult aclresult;
583 
584  /*
585  * Parse and check options.
586  *
587  * Connection and publication should not be specified here.
588  */
589  supported_opts = (SUBOPT_CONNECT | SUBOPT_ENABLED | SUBOPT_CREATE_SLOT |
595  parse_subscription_options(pstate, stmt->options, supported_opts, &opts);
596 
597  /*
598  * Since creating a replication slot is not transactional, rolling back
599  * the transaction leaves the created replication slot. So we cannot run
600  * CREATE SUBSCRIPTION inside a transaction block if creating a
601  * replication slot.
602  */
603  if (opts.create_slot)
604  PreventInTransactionBlock(isTopLevel, "CREATE SUBSCRIPTION ... WITH (create_slot = true)");
605 
606  /*
607  * We don't want to allow unprivileged users to be able to trigger
608  * attempts to access arbitrary network destinations, so require the user
609  * to have been specifically authorized to create subscriptions.
610  */
611  if (!has_privs_of_role(owner, ROLE_PG_CREATE_SUBSCRIPTION))
612  ereport(ERROR,
613  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
614  errmsg("permission denied to create subscription"),
615  errdetail("Only roles with privileges of the \"%s\" role may create subscriptions.",
616  "pg_create_subscription")));
617 
618  /*
619  * Since a subscription is a database object, we also check for CREATE
620  * permission on the database.
621  */
622  aclresult = object_aclcheck(DatabaseRelationId, MyDatabaseId,
623  owner, ACL_CREATE);
624  if (aclresult != ACLCHECK_OK)
625  aclcheck_error(aclresult, OBJECT_DATABASE,
627 
628  /*
629  * Non-superusers are required to set a password for authentication, and
630  * that password must be used by the target server, but the superuser can
631  * exempt a subscription from this requirement.
632  */
633  if (!opts.passwordrequired && !superuser_arg(owner))
634  ereport(ERROR,
635  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
636  errmsg("password_required=false is superuser-only"),
637  errhint("Subscriptions with the password_required option set to false may only be created or modified by the superuser.")));
638 
639  /*
640  * If built with appropriate switch, whine when regression-testing
641  * conventions for subscription names are violated.
642  */
643 #ifdef ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS
644  if (strncmp(stmt->subname, "regress_", 8) != 0)
645  elog(WARNING, "subscriptions created by regression test cases should have names starting with \"regress_\"");
646 #endif
647 
648  rel = table_open(SubscriptionRelationId, RowExclusiveLock);
649 
650  /* Check if name is used */
651  subid = GetSysCacheOid2(SUBSCRIPTIONNAME, Anum_pg_subscription_oid,
652  MyDatabaseId, CStringGetDatum(stmt->subname));
653  if (OidIsValid(subid))
654  {
655  ereport(ERROR,
657  errmsg("subscription \"%s\" already exists",
658  stmt->subname)));
659  }
660 
661  if (!IsSet(opts.specified_opts, SUBOPT_SLOT_NAME) &&
662  opts.slot_name == NULL)
663  opts.slot_name = stmt->subname;
664 
665  /* The default for synchronous_commit of subscriptions is off. */
666  if (opts.synchronous_commit == NULL)
667  opts.synchronous_commit = "off";
668 
669  conninfo = stmt->conninfo;
670  publications = stmt->publication;
671 
672  /* Load the library providing us libpq calls. */
673  load_file("libpqwalreceiver", false);
674 
675  /* Check the connection info string. */
676  walrcv_check_conninfo(conninfo, opts.passwordrequired && !superuser());
677 
678  /* Everything ok, form a new tuple. */
679  memset(values, 0, sizeof(values));
680  memset(nulls, false, sizeof(nulls));
681 
682  subid = GetNewOidWithIndex(rel, SubscriptionObjectIndexId,
683  Anum_pg_subscription_oid);
684  values[Anum_pg_subscription_oid - 1] = ObjectIdGetDatum(subid);
685  values[Anum_pg_subscription_subdbid - 1] = ObjectIdGetDatum(MyDatabaseId);
686  values[Anum_pg_subscription_subskiplsn - 1] = LSNGetDatum(InvalidXLogRecPtr);
687  values[Anum_pg_subscription_subname - 1] =
689  values[Anum_pg_subscription_subowner - 1] = ObjectIdGetDatum(owner);
690  values[Anum_pg_subscription_subenabled - 1] = BoolGetDatum(opts.enabled);
691  values[Anum_pg_subscription_subbinary - 1] = BoolGetDatum(opts.binary);
692  values[Anum_pg_subscription_substream - 1] = CharGetDatum(opts.streaming);
693  values[Anum_pg_subscription_subtwophasestate - 1] =
694  CharGetDatum(opts.twophase ?
697  values[Anum_pg_subscription_subdisableonerr - 1] = BoolGetDatum(opts.disableonerr);
698  values[Anum_pg_subscription_subpasswordrequired - 1] = BoolGetDatum(opts.passwordrequired);
699  values[Anum_pg_subscription_subrunasowner - 1] = BoolGetDatum(opts.runasowner);
700  values[Anum_pg_subscription_subconninfo - 1] =
701  CStringGetTextDatum(conninfo);
702  if (opts.slot_name)
703  values[Anum_pg_subscription_subslotname - 1] =
705  else
706  nulls[Anum_pg_subscription_subslotname - 1] = true;
707  values[Anum_pg_subscription_subsynccommit - 1] =
708  CStringGetTextDatum(opts.synchronous_commit);
709  values[Anum_pg_subscription_subpublications - 1] =
710  publicationListToArray(publications);
711  values[Anum_pg_subscription_suborigin - 1] =
712  CStringGetTextDatum(opts.origin);
713 
714  tup = heap_form_tuple(RelationGetDescr(rel), values, nulls);
715 
716  /* Insert tuple into catalog. */
717  CatalogTupleInsert(rel, tup);
718  heap_freetuple(tup);
719 
720  recordDependencyOnOwner(SubscriptionRelationId, subid, owner);
721 
722  ReplicationOriginNameForLogicalRep(subid, InvalidOid, originname, sizeof(originname));
723  replorigin_create(originname);
724 
725  /*
726  * Connect to remote side to execute requested commands and fetch table
727  * info.
728  */
729  if (opts.connect)
730  {
731  char *err;
733  List *tables;
734  ListCell *lc;
735  char table_state;
736  bool must_use_password;
737 
738  /* Try to connect to the publisher. */
739  must_use_password = !superuser_arg(owner) && opts.passwordrequired;
740  wrconn = walrcv_connect(conninfo, true, must_use_password,
741  stmt->subname, &err);
742  if (!wrconn)
743  ereport(ERROR,
744  (errcode(ERRCODE_CONNECTION_FAILURE),
745  errmsg("could not connect to the publisher: %s", err)));
746 
747  PG_TRY();
748  {
749  check_publications(wrconn, publications);
750  check_publications_origin(wrconn, publications, opts.copy_data,
751  opts.origin, NULL, 0, stmt->subname);
752 
753  /*
754  * Set sync state based on if we were asked to do data copy or
755  * not.
756  */
757  table_state = opts.copy_data ? SUBREL_STATE_INIT : SUBREL_STATE_READY;
758 
759  /*
760  * Get the table list from publisher and build local table status
761  * info.
762  */
763  tables = fetch_table_list(wrconn, publications);
764  foreach(lc, tables)
765  {
766  RangeVar *rv = (RangeVar *) lfirst(lc);
767  Oid relid;
768 
769  relid = RangeVarGetRelid(rv, AccessShareLock, false);
770 
771  /* Check for supported relkind. */
773  rv->schemaname, rv->relname);
774 
775  AddSubscriptionRelState(subid, relid, table_state,
777  }
778 
779  /*
780  * If requested, create permanent slot for the subscription. We
781  * won't use the initial snapshot for anything, so no need to
782  * export it.
783  */
784  if (opts.create_slot)
785  {
786  bool twophase_enabled = false;
787 
788  Assert(opts.slot_name);
789 
790  /*
791  * Even if two_phase is set, don't create the slot with
792  * two-phase enabled. Will enable it once all the tables are
793  * synced and ready. This avoids race-conditions like prepared
794  * transactions being skipped due to changes not being applied
795  * due to checks in should_apply_changes_for_rel() when
796  * tablesync for the corresponding tables are in progress. See
797  * comments atop worker.c.
798  *
799  * Note that if tables were specified but copy_data is false
800  * then it is safe to enable two_phase up-front because those
801  * tables are already initially in READY state. When the
802  * subscription has no tables, we leave the twophase state as
803  * PENDING, to allow ALTER SUBSCRIPTION ... REFRESH
804  * PUBLICATION to work.
805  */
806  if (opts.twophase && !opts.copy_data && tables != NIL)
807  twophase_enabled = true;
808 
809  walrcv_create_slot(wrconn, opts.slot_name, false, twophase_enabled,
810  CRS_NOEXPORT_SNAPSHOT, NULL);
811 
812  if (twophase_enabled)
814 
815  ereport(NOTICE,
816  (errmsg("created replication slot \"%s\" on publisher",
817  opts.slot_name)));
818  }
819  }
820  PG_FINALLY();
821  {
823  }
824  PG_END_TRY();
825  }
826  else
828  (errmsg("subscription was created, but is not connected"),
829  errhint("To initiate replication, you must manually create the replication slot, enable the subscription, and refresh the subscription.")));
830 
832 
834 
835  if (opts.enabled)
837 
838  ObjectAddressSet(myself, SubscriptionRelationId, subid);
839 
840  InvokeObjectPostCreateHook(SubscriptionRelationId, subid, 0);
841 
842  return myself;
843 }
bool has_privs_of_role(Oid member, Oid role)
Definition: acl.c:4961
#define OidIsValid(objectId)
Definition: c.h:764
Oid GetNewOidWithIndex(Relation relation, Oid indexId, AttrNumber oidcolumn)
Definition: catalog.c:393
int errdetail(const char *fmt,...)
Definition: elog.c:1202
#define NOTICE
Definition: elog.h:35
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1108
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:233
#define InvokeObjectPostCreateHook(classId, objectId, subId)
Definition: objectaccess.h:173
RepOriginId replorigin_create(const char *roname)
Definition: origin.c:252
void recordDependencyOnOwner(Oid classId, Oid objectId, Oid owner)
Definition: pg_shdepend.c:165
#define LOGICALREP_TWOPHASE_STATE_DISABLED
#define LOGICALREP_TWOPHASE_STATE_PENDING
void pgstat_create_subscription(Oid subid)
#define SUBOPT_CREATE_SLOT
#define SUBOPT_TWOPHASE_COMMIT
#define SUBOPT_CONNECT
#define GetSysCacheOid2(cacheId, oidcol, key1, key2)
Definition: syscache.h:202
void UpdateTwoPhaseState(Oid suboid, char new_state)
Definition: tablesync.c:1722
#define walrcv_create_slot(conn, slotname, temporary, two_phase, snapshot_action, lsn)
Definition: walreceiver.h:432
@ CRS_NOEXPORT_SNAPSHOT
Definition: walsender.h:23

References AccessShareLock, ACL_CREATE, aclcheck_error(), ACLCHECK_OK, AddSubscriptionRelState(), ApplyLauncherWakeupAtCommit(), Assert(), BoolGetDatum(), CatalogTupleInsert(), CharGetDatum(), check_publications(), check_publications_origin(), CheckSubscriptionRelkind(), CRS_NOEXPORT_SNAPSHOT, CStringGetDatum(), CStringGetTextDatum, DirectFunctionCall1, elog(), ereport, err(), errcode(), ERRCODE_DUPLICATE_OBJECT, errdetail(), errhint(), errmsg(), ERROR, fetch_table_list(), get_database_name(), get_rel_relkind(), GetNewOidWithIndex(), GetSysCacheOid2, GetUserId(), has_privs_of_role(), heap_form_tuple(), heap_freetuple(), InvalidOid, InvalidXLogRecPtr, InvokeObjectPostCreateHook, IsSet, lfirst, load_file(), LOGICALREP_TWOPHASE_STATE_DISABLED, LOGICALREP_TWOPHASE_STATE_ENABLED, LOGICALREP_TWOPHASE_STATE_PENDING, LSNGetDatum(), MyDatabaseId, NAMEDATALEN, namein(), NIL, NOTICE, object_aclcheck(), OBJECT_DATABASE, ObjectAddressSet, ObjectIdGetDatum(), OidIsValid, opts, parse_subscription_options(), PG_END_TRY, PG_FINALLY, PG_TRY, pgstat_create_subscription(), PreventInTransactionBlock(), publicationListToArray(), RangeVarGetRelid, recordDependencyOnOwner(), RelationGetDescr, RangeVar::relname, ReplicationOriginNameForLogicalRep(), replorigin_create(), RowExclusiveLock, RangeVar::schemaname, stmt, SUBOPT_BINARY, SUBOPT_CONNECT, SUBOPT_COPY_DATA, SUBOPT_CREATE_SLOT, SUBOPT_DISABLE_ON_ERR, SUBOPT_ENABLED, SUBOPT_ORIGIN, SUBOPT_PASSWORD_REQUIRED, SUBOPT_RUN_AS_OWNER, SUBOPT_SLOT_NAME, SUBOPT_STREAMING, SUBOPT_SYNCHRONOUS_COMMIT, SUBOPT_TWOPHASE_COMMIT, SUBSCRIPTIONNAME, superuser(), superuser_arg(), table_close(), table_open(), UpdateTwoPhaseState(), values, walrcv_check_conninfo, walrcv_connect, walrcv_create_slot, walrcv_disconnect, WARNING, and wrconn.

Referenced by ProcessUtilitySlow().

◆ defGetStreamingMode()

char defGetStreamingMode ( DefElem def)

Definition at line 2305 of file subscriptioncmds.c.

2306 {
2307  /*
2308  * If no parameter value given, assume "true" is meant.
2309  */
2310  if (!def->arg)
2311  return LOGICALREP_STREAM_ON;
2312 
2313  /*
2314  * Allow 0, 1, "false", "true", "off", "on" or "parallel".
2315  */
2316  switch (nodeTag(def->arg))
2317  {
2318  case T_Integer:
2319  switch (intVal(def->arg))
2320  {
2321  case 0:
2322  return LOGICALREP_STREAM_OFF;
2323  case 1:
2324  return LOGICALREP_STREAM_ON;
2325  default:
2326  /* otherwise, error out below */
2327  break;
2328  }
2329  break;
2330  default:
2331  {
2332  char *sval = defGetString(def);
2333 
2334  /*
2335  * The set of strings accepted here should match up with the
2336  * grammar's opt_boolean_or_string production.
2337  */
2338  if (pg_strcasecmp(sval, "false") == 0 ||
2339  pg_strcasecmp(sval, "off") == 0)
2340  return LOGICALREP_STREAM_OFF;
2341  if (pg_strcasecmp(sval, "true") == 0 ||
2342  pg_strcasecmp(sval, "on") == 0)
2343  return LOGICALREP_STREAM_ON;
2344  if (pg_strcasecmp(sval, "parallel") == 0)
2346  }
2347  break;
2348  }
2349 
2350  ereport(ERROR,
2351  (errcode(ERRCODE_SYNTAX_ERROR),
2352  errmsg("%s requires a Boolean value or \"parallel\"",
2353  def->defname)));
2354  return LOGICALREP_STREAM_OFF; /* keep compiler quiet */
2355 }
char * defGetString(DefElem *def)
Definition: define.c:49
#define nodeTag(nodeptr)
Definition: nodes.h:133
#define LOGICALREP_STREAM_ON
#define LOGICALREP_STREAM_OFF
#define LOGICALREP_STREAM_PARALLEL
char * defname
Definition: parsenodes.h:809
Node * arg
Definition: parsenodes.h:810
#define intVal(v)
Definition: value.h:79

References DefElem::arg, defGetString(), DefElem::defname, ereport, errcode(), errmsg(), ERROR, intVal, LOGICALREP_STREAM_OFF, LOGICALREP_STREAM_ON, LOGICALREP_STREAM_PARALLEL, nodeTag, and pg_strcasecmp().

Referenced by parse_output_parameters(), and parse_subscription_options().

◆ DropSubscription()

void DropSubscription ( DropSubscriptionStmt stmt,
bool  isTopLevel 
)

Definition at line 1472 of file subscriptioncmds.c.

1473 {
1474  Relation rel;
1475  ObjectAddress myself;
1476  HeapTuple tup;
1477  Oid subid;
1478  Oid subowner;
1479  Datum datum;
1480  bool isnull;
1481  char *subname;
1482  char *conninfo;
1483  char *slotname;
1484  List *subworkers;
1485  ListCell *lc;
1486  char originname[NAMEDATALEN];
1487  char *err = NULL;
1489  Form_pg_subscription form;
1490  List *rstates;
1491  bool must_use_password;
1492 
1493  /*
1494  * Lock pg_subscription with AccessExclusiveLock to ensure that the
1495  * launcher doesn't restart new worker during dropping the subscription
1496  */
1497  rel = table_open(SubscriptionRelationId, AccessExclusiveLock);
1498 
1500  CStringGetDatum(stmt->subname));
1501 
1502  if (!HeapTupleIsValid(tup))
1503  {
1504  table_close(rel, NoLock);
1505 
1506  if (!stmt->missing_ok)
1507  ereport(ERROR,
1508  (errcode(ERRCODE_UNDEFINED_OBJECT),
1509  errmsg("subscription \"%s\" does not exist",
1510  stmt->subname)));
1511  else
1512  ereport(NOTICE,
1513  (errmsg("subscription \"%s\" does not exist, skipping",
1514  stmt->subname)));
1515 
1516  return;
1517  }
1518 
1519  form = (Form_pg_subscription) GETSTRUCT(tup);
1520  subid = form->oid;
1521  subowner = form->subowner;
1522  must_use_password = !superuser_arg(subowner) && form->subpasswordrequired;
1523 
1524  /* must be owner */
1525  if (!object_ownercheck(SubscriptionRelationId, subid, GetUserId()))
1527  stmt->subname);
1528 
1529  /* DROP hook for the subscription being removed */
1530  InvokeObjectDropHook(SubscriptionRelationId, subid, 0);
1531 
1532  /*
1533  * Lock the subscription so nobody else can do anything with it (including
1534  * the replication workers).
1535  */
1536  LockSharedObject(SubscriptionRelationId, subid, 0, AccessExclusiveLock);
1537 
1538  /* Get subname */
1540  Anum_pg_subscription_subname);
1541  subname = pstrdup(NameStr(*DatumGetName(datum)));
1542 
1543  /* Get conninfo */
1545  Anum_pg_subscription_subconninfo);
1546  conninfo = TextDatumGetCString(datum);
1547 
1548  /* Get slotname */
1549  datum = SysCacheGetAttr(SUBSCRIPTIONOID, tup,
1550  Anum_pg_subscription_subslotname, &isnull);
1551  if (!isnull)
1552  slotname = pstrdup(NameStr(*DatumGetName(datum)));
1553  else
1554  slotname = NULL;
1555 
1556  /*
1557  * Since dropping a replication slot is not transactional, the replication
1558  * slot stays dropped even if the transaction rolls back. So we cannot
1559  * run DROP SUBSCRIPTION inside a transaction block if dropping the
1560  * replication slot. Also, in this case, we report a message for dropping
1561  * the subscription to the cumulative stats system.
1562  *
1563  * XXX The command name should really be something like "DROP SUBSCRIPTION
1564  * of a subscription that is associated with a replication slot", but we
1565  * don't have the proper facilities for that.
1566  */
1567  if (slotname)
1568  PreventInTransactionBlock(isTopLevel, "DROP SUBSCRIPTION");
1569 
1570  ObjectAddressSet(myself, SubscriptionRelationId, subid);
1571  EventTriggerSQLDropAddObject(&myself, true, true);
1572 
1573  /* Remove the tuple from catalog. */
1574  CatalogTupleDelete(rel, &tup->t_self);
1575 
1576  ReleaseSysCache(tup);
1577 
1578  /*
1579  * Stop all the subscription workers immediately.
1580  *
1581  * This is necessary if we are dropping the replication slot, so that the
1582  * slot becomes accessible.
1583  *
1584  * It is also necessary if the subscription is disabled and was disabled
1585  * in the same transaction. Then the workers haven't seen the disabling
1586  * yet and will still be running, leading to hangs later when we want to
1587  * drop the replication origin. If the subscription was disabled before
1588  * this transaction, then there shouldn't be any workers left, so this
1589  * won't make a difference.
1590  *
1591  * New workers won't be started because we hold an exclusive lock on the
1592  * subscription till the end of the transaction.
1593  */
1594  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
1595  subworkers = logicalrep_workers_find(subid, false);
1596  LWLockRelease(LogicalRepWorkerLock);
1597  foreach(lc, subworkers)
1598  {
1600 
1602  }
1603  list_free(subworkers);
1604 
1605  /*
1606  * Remove the no-longer-useful entry in the launcher's table of apply
1607  * worker start times.
1608  *
1609  * If this transaction rolls back, the launcher might restart a failed
1610  * apply worker before wal_retrieve_retry_interval milliseconds have
1611  * elapsed, but that's pretty harmless.
1612  */
1614 
1615  /*
1616  * Cleanup of tablesync replication origins.
1617  *
1618  * Any READY-state relations would already have dealt with clean-ups.
1619  *
1620  * Note that the state can't change because we have already stopped both
1621  * the apply and tablesync workers and they can't restart because of
1622  * exclusive lock on the subscription.
1623  */
1624  rstates = GetSubscriptionRelations(subid, true);
1625  foreach(lc, rstates)
1626  {
1628  Oid relid = rstate->relid;
1629 
1630  /* Only cleanup resources of tablesync workers */
1631  if (!OidIsValid(relid))
1632  continue;
1633 
1634  /*
1635  * Drop the tablesync's origin tracking if exists.
1636  *
1637  * It is possible that the origin is not yet created for tablesync
1638  * worker so passing missing_ok = true. This can happen for the states
1639  * before SUBREL_STATE_FINISHEDCOPY.
1640  */
1641  ReplicationOriginNameForLogicalRep(subid, relid, originname,
1642  sizeof(originname));
1643  replorigin_drop_by_name(originname, true, false);
1644  }
1645 
1646  /* Clean up dependencies */
1647  deleteSharedDependencyRecordsFor(SubscriptionRelationId, subid, 0);
1648 
1649  /* Remove any associated relation synchronization states. */
1651 
1652  /* Remove the origin tracking if exists. */
1653  ReplicationOriginNameForLogicalRep(subid, InvalidOid, originname, sizeof(originname));
1654  replorigin_drop_by_name(originname, true, false);
1655 
1656  /*
1657  * Tell the cumulative stats system that the subscription is getting
1658  * dropped.
1659  */
1660  pgstat_drop_subscription(subid);
1661 
1662  /*
1663  * If there is no slot associated with the subscription, we can finish
1664  * here.
1665  */
1666  if (!slotname && rstates == NIL)
1667  {
1668  table_close(rel, NoLock);
1669  return;
1670  }
1671 
1672  /*
1673  * Try to acquire the connection necessary for dropping slots.
1674  *
1675  * Note: If the slotname is NONE/NULL then we allow the command to finish
1676  * and users need to manually cleanup the apply and tablesync worker slots
1677  * later.
1678  *
1679  * This has to be at the end because otherwise if there is an error while
1680  * doing the database operations we won't be able to rollback dropped
1681  * slot.
1682  */
1683  load_file("libpqwalreceiver", false);
1684 
1685  wrconn = walrcv_connect(conninfo, true, must_use_password,
1686  subname, &err);
1687  if (wrconn == NULL)
1688  {
1689  if (!slotname)
1690  {
1691  /* be tidy */
1692  list_free(rstates);
1693  table_close(rel, NoLock);
1694  return;
1695  }
1696  else
1697  {
1698  ReportSlotConnectionError(rstates, subid, slotname, err);
1699  }
1700  }
1701 
1702  PG_TRY();
1703  {
1704  foreach(lc, rstates)
1705  {
1707  Oid relid = rstate->relid;
1708 
1709  /* Only cleanup resources of tablesync workers */
1710  if (!OidIsValid(relid))
1711  continue;
1712 
1713  /*
1714  * Drop the tablesync slots associated with removed tables.
1715  *
1716  * For SYNCDONE/READY states, the tablesync slot is known to have
1717  * already been dropped by the tablesync worker.
1718  *
1719  * For other states, there is no certainty, maybe the slot does
1720  * not exist yet. Also, if we fail after removing some of the
1721  * slots, next time, it will again try to drop already dropped
1722  * slots and fail. For these reasons, we allow missing_ok = true
1723  * for the drop.
1724  */
1725  if (rstate->state != SUBREL_STATE_SYNCDONE)
1726  {
1727  char syncslotname[NAMEDATALEN] = {0};
1728 
1729  ReplicationSlotNameForTablesync(subid, relid, syncslotname,
1730  sizeof(syncslotname));
1731  ReplicationSlotDropAtPubNode(wrconn, syncslotname, true);
1732  }
1733  }
1734 
1735  list_free(rstates);
1736 
1737  /*
1738  * If there is a slot associated with the subscription, then drop the
1739  * replication slot at the publisher.
1740  */
1741  if (slotname)
1742  ReplicationSlotDropAtPubNode(wrconn, slotname, false);
1743  }
1744  PG_FINALLY();
1745  {
1747  }
1748  PG_END_TRY();
1749 
1750  table_close(rel, NoLock);
1751 }
void EventTriggerSQLDropAddObject(const ObjectAddress *object, bool original, bool normal)
void CatalogTupleDelete(Relation heapRel, ItemPointer tid)
Definition: indexing.c:365
List * logicalrep_workers_find(Oid subid, bool only_running)
Definition: launcher.c:281
void ApplyLauncherForgetWorkerStartTime(Oid subid)
Definition: launcher.c:1074
void list_free(List *list)
Definition: list.c:1545
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1195
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1808
@ LW_SHARED
Definition: lwlock.h:117
char * pstrdup(const char *in)
Definition: mcxt.c:1644
#define InvokeObjectDropHook(classId, objectId, subId)
Definition: objectaccess.h:182
void deleteSharedDependencyRecordsFor(Oid classId, Oid objectId, int32 objectSubId)
Definition: pg_shdepend.c:1002
void pgstat_drop_subscription(Oid subid)
static Name DatumGetName(Datum X)
Definition: postgres.h:360
static void ReportSlotConnectionError(List *rstates, Oid subid, char *slotname, char *err)
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:868
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1081
HeapTuple SearchSysCache2(int cacheId, Datum key1, Datum key2)
Definition: syscache.c:831
Datum SysCacheGetAttrNotNull(int cacheId, HeapTuple tup, AttrNumber attributeNumber)
Definition: syscache.c:1112

References AccessExclusiveLock, aclcheck_error(), ACLCHECK_NOT_OWNER, ApplyLauncherForgetWorkerStartTime(), CatalogTupleDelete(), CStringGetDatum(), DatumGetName(), deleteSharedDependencyRecordsFor(), ereport, err(), errcode(), errmsg(), ERROR, EventTriggerSQLDropAddObject(), GETSTRUCT, GetSubscriptionRelations(), GetUserId(), HeapTupleIsValid, InvalidOid, InvokeObjectDropHook, lfirst, list_free(), load_file(), LockSharedObject(), logicalrep_worker_stop(), logicalrep_workers_find(), LW_SHARED, LWLockAcquire(), LWLockRelease(), MyDatabaseId, NAMEDATALEN, NameStr, NIL, NoLock, NOTICE, object_ownercheck(), OBJECT_SUBSCRIPTION, ObjectAddressSet, OidIsValid, PG_END_TRY, PG_FINALLY, PG_TRY, pgstat_drop_subscription(), PreventInTransactionBlock(), pstrdup(), ReleaseSysCache(), SubscriptionRelState::relid, LogicalRepWorker::relid, RemoveSubscriptionRel(), ReplicationOriginNameForLogicalRep(), ReplicationSlotDropAtPubNode(), ReplicationSlotNameForTablesync(), replorigin_drop_by_name(), ReportSlotConnectionError(), SearchSysCache2(), SubscriptionRelState::state, stmt, LogicalRepWorker::subid, subname, SUBSCRIPTIONNAME, SUBSCRIPTIONOID, superuser_arg(), SysCacheGetAttr(), SysCacheGetAttrNotNull(), 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 2054 of file subscriptioncmds.c.

2055 {
2057  StringInfoData cmd;
2058  TupleTableSlot *slot;
2059  Oid tableRow[3] = {TEXTOID, TEXTOID, InvalidOid};
2060  List *tablelist = NIL;
2062  bool check_columnlist = (server_version >= 150000);
2063 
2064  initStringInfo(&cmd);
2065 
2066  /* Get the list of tables from the publisher. */
2067  if (server_version >= 160000)
2068  {
2069  StringInfoData pub_names;
2070 
2071  tableRow[2] = INT2VECTOROID;
2072  initStringInfo(&pub_names);
2073  get_publications_str(publications, &pub_names, true);
2074 
2075  /*
2076  * From version 16, we allowed passing multiple publications to the
2077  * function pg_get_publication_tables. This helped to filter out the
2078  * partition table whose ancestor is also published in this
2079  * publication array.
2080  *
2081  * Join pg_get_publication_tables with pg_publication to exclude
2082  * non-existing publications.
2083  *
2084  * Note that attrs are always stored in sorted order so we don't need
2085  * to worry if different publications have specified them in a
2086  * different order. See publication_translate_columns.
2087  */
2088  appendStringInfo(&cmd, "SELECT DISTINCT n.nspname, c.relname, gpt.attrs\n"
2089  " FROM pg_class c\n"
2090  " JOIN pg_namespace n ON n.oid = c.relnamespace\n"
2091  " JOIN ( SELECT (pg_get_publication_tables(VARIADIC array_agg(pubname::text))).*\n"
2092  " FROM pg_publication\n"
2093  " WHERE pubname IN ( %s )) AS gpt\n"
2094  " ON gpt.relid = c.oid\n",
2095  pub_names.data);
2096 
2097  pfree(pub_names.data);
2098  }
2099  else
2100  {
2101  tableRow[2] = NAMEARRAYOID;
2102  appendStringInfoString(&cmd, "SELECT DISTINCT t.schemaname, t.tablename \n");
2103 
2104  /* Get column lists for each relation if the publisher supports it */
2105  if (check_columnlist)
2106  appendStringInfoString(&cmd, ", t.attnames\n");
2107 
2108  appendStringInfoString(&cmd, "FROM pg_catalog.pg_publication_tables t\n"
2109  " WHERE t.pubname IN (");
2110  get_publications_str(publications, &cmd, true);
2111  appendStringInfoChar(&cmd, ')');
2112  }
2113 
2114  res = walrcv_exec(wrconn, cmd.data, check_columnlist ? 3 : 2, tableRow);
2115  pfree(cmd.data);
2116 
2117  if (res->status != WALRCV_OK_TUPLES)
2118  ereport(ERROR,
2119  (errcode(ERRCODE_CONNECTION_FAILURE),
2120  errmsg("could not receive list of replicated tables from the publisher: %s",
2121  res->err)));
2122 
2123  /* Process tables. */
2124  slot = MakeSingleTupleTableSlot(res->tupledesc, &TTSOpsMinimalTuple);
2125  while (tuplestore_gettupleslot(res->tuplestore, true, false, slot))
2126  {
2127  char *nspname;
2128  char *relname;
2129  bool isnull;
2130  RangeVar *rv;
2131 
2132  nspname = TextDatumGetCString(slot_getattr(slot, 1, &isnull));
2133  Assert(!isnull);
2134  relname = TextDatumGetCString(slot_getattr(slot, 2, &isnull));
2135  Assert(!isnull);
2136 
2137  rv = makeRangeVar(nspname, relname, -1);
2138 
2139  if (check_columnlist && list_member(tablelist, rv))
2140  ereport(ERROR,
2141  errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2142  errmsg("cannot use different column lists for table \"%s.%s\" in different publications",
2143  nspname, relname));
2144  else
2145  tablelist = lappend(tablelist, rv);
2146 
2147  ExecClearTuple(slot);
2148  }
2150 
2152 
2153  return tablelist;
2154 }
List * lappend(List *list, void *datum)
Definition: list.c:338
bool list_member(const List *list, const void *datum)
Definition: list.c:660
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:425
NameData relname
Definition: pg_class.h:38
static int server_version
Definition: pg_dumpall.c:110
#define walrcv_server_version(conn)
Definition: walreceiver.h:420

References appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), Assert(), StringInfoData::data, ereport, errcode(), errmsg(), ERROR, ExecClearTuple(), ExecDropSingleTupleTableSlot(), get_publications_str(), initStringInfo(), InvalidOid, lappend(), list_member(), makeRangeVar(), MakeSingleTupleTableSlot(), NIL, pfree(), relname, res, server_version, slot_getattr(), TextDatumGetCString, TTSOpsMinimalTuple, tuplestore_gettupleslot(), walrcv_clear_result(), walrcv_exec, WALRCV_OK_TUPLES, walrcv_server_version, 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 442 of file subscriptioncmds.c.

443 {
444  ListCell *lc;
445  bool first = true;
446 
447  Assert(publications != NIL);
448 
449  foreach(lc, publications)
450  {
451  char *pubname = strVal(lfirst(lc));
452 
453  if (first)
454  first = false;
455  else
457 
458  if (quote_literal)
460  else
461  {
463  appendStringInfoString(dest, pubname);
465  }
466  }
467 }
char * quote_literal_cstr(const char *rawstr)
Definition: quote.c:103
Datum quote_literal(PG_FUNCTION_ARGS)
Definition: quote.c:78

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

Referenced by check_publications(), check_publications_origin(), and fetch_table_list().

◆ merge_publications()

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

Definition at line 2246 of file subscriptioncmds.c.

2247 {
2248  ListCell *lc;
2249 
2250  oldpublist = list_copy(oldpublist);
2251 
2252  check_duplicates_in_publist(newpublist, NULL);
2253 
2254  foreach(lc, newpublist)
2255  {
2256  char *name = strVal(lfirst(lc));
2257  ListCell *lc2;
2258  bool found = false;
2259 
2260  foreach(lc2, oldpublist)
2261  {
2262  char *pubname = strVal(lfirst(lc2));
2263 
2264  if (strcmp(name, pubname) == 0)
2265  {
2266  found = true;
2267  if (addpub)
2268  ereport(ERROR,
2270  errmsg("publication \"%s\" is already in subscription \"%s\"",
2271  name, subname)));
2272  else
2273  oldpublist = foreach_delete_current(oldpublist, lc2);
2274 
2275  break;
2276  }
2277  }
2278 
2279  if (addpub && !found)
2280  oldpublist = lappend(oldpublist, makeString(name));
2281  else if (!addpub && !found)
2282  ereport(ERROR,
2283  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2284  errmsg("publication \"%s\" is not in subscription \"%s\"",
2285  name, subname)));
2286  }
2287 
2288  /*
2289  * XXX Probably no strong reason for this, but for now it's to make ALTER
2290  * SUBSCRIPTION ... DROP PUBLICATION consistent with SET PUBLICATION.
2291  */
2292  if (!oldpublist)
2293  ereport(ERROR,
2294  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
2295  errmsg("cannot drop all the publications from a subscription")));
2296 
2297  return oldpublist;
2298 }
#define foreach_delete_current(lst, cell)
Definition: pg_list.h:390
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 119 of file subscriptioncmds.c.

121 {
122  ListCell *lc;
123 
124  /* Start out with cleared opts. */
125  memset(opts, 0, sizeof(SubOpts));
126 
127  /* caller must expect some option */
128  Assert(supported_opts != 0);
129 
130  /* If connect option is supported, these others also need to be. */
131  Assert(!IsSet(supported_opts, SUBOPT_CONNECT) ||
132  IsSet(supported_opts, SUBOPT_ENABLED | SUBOPT_CREATE_SLOT |
134 
135  /* Set default values for the supported options. */
136  if (IsSet(supported_opts, SUBOPT_CONNECT))
137  opts->connect = true;
138  if (IsSet(supported_opts, SUBOPT_ENABLED))
139  opts->enabled = true;
140  if (IsSet(supported_opts, SUBOPT_CREATE_SLOT))
141  opts->create_slot = true;
142  if (IsSet(supported_opts, SUBOPT_COPY_DATA))
143  opts->copy_data = true;
144  if (IsSet(supported_opts, SUBOPT_REFRESH))
145  opts->refresh = true;
146  if (IsSet(supported_opts, SUBOPT_BINARY))
147  opts->binary = false;
148  if (IsSet(supported_opts, SUBOPT_STREAMING))
149  opts->streaming = LOGICALREP_STREAM_OFF;
150  if (IsSet(supported_opts, SUBOPT_TWOPHASE_COMMIT))
151  opts->twophase = false;
152  if (IsSet(supported_opts, SUBOPT_DISABLE_ON_ERR))
153  opts->disableonerr = false;
154  if (IsSet(supported_opts, SUBOPT_PASSWORD_REQUIRED))
155  opts->passwordrequired = true;
156  if (IsSet(supported_opts, SUBOPT_RUN_AS_OWNER))
157  opts->runasowner = false;
158  if (IsSet(supported_opts, SUBOPT_ORIGIN))
160 
161  /* Parse options */
162  foreach(lc, stmt_options)
163  {
164  DefElem *defel = (DefElem *) lfirst(lc);
165 
166  if (IsSet(supported_opts, SUBOPT_CONNECT) &&
167  strcmp(defel->defname, "connect") == 0)
168  {
169  if (IsSet(opts->specified_opts, SUBOPT_CONNECT))
170  errorConflictingDefElem(defel, pstate);
171 
172  opts->specified_opts |= SUBOPT_CONNECT;
173  opts->connect = defGetBoolean(defel);
174  }
175  else if (IsSet(supported_opts, SUBOPT_ENABLED) &&
176  strcmp(defel->defname, "enabled") == 0)
177  {
178  if (IsSet(opts->specified_opts, SUBOPT_ENABLED))
179  errorConflictingDefElem(defel, pstate);
180 
181  opts->specified_opts |= SUBOPT_ENABLED;
182  opts->enabled = defGetBoolean(defel);
183  }
184  else if (IsSet(supported_opts, SUBOPT_CREATE_SLOT) &&
185  strcmp(defel->defname, "create_slot") == 0)
186  {
187  if (IsSet(opts->specified_opts, SUBOPT_CREATE_SLOT))
188  errorConflictingDefElem(defel, pstate);
189 
190  opts->specified_opts |= SUBOPT_CREATE_SLOT;
191  opts->create_slot = defGetBoolean(defel);
192  }
193  else if (IsSet(supported_opts, SUBOPT_SLOT_NAME) &&
194  strcmp(defel->defname, "slot_name") == 0)
195  {
196  if (IsSet(opts->specified_opts, SUBOPT_SLOT_NAME))
197  errorConflictingDefElem(defel, pstate);
198 
199  opts->specified_opts |= SUBOPT_SLOT_NAME;
200  opts->slot_name = defGetString(defel);
201 
202  /* Setting slot_name = NONE is treated as no slot name. */
203  if (strcmp(opts->slot_name, "none") == 0)
204  opts->slot_name = NULL;
205  else
207  }
208  else if (IsSet(supported_opts, SUBOPT_COPY_DATA) &&
209  strcmp(defel->defname, "copy_data") == 0)
210  {
211  if (IsSet(opts->specified_opts, SUBOPT_COPY_DATA))
212  errorConflictingDefElem(defel, pstate);
213 
214  opts->specified_opts |= SUBOPT_COPY_DATA;
215  opts->copy_data = defGetBoolean(defel);
216  }
217  else if (IsSet(supported_opts, SUBOPT_SYNCHRONOUS_COMMIT) &&
218  strcmp(defel->defname, "synchronous_commit") == 0)
219  {
220  if (IsSet(opts->specified_opts, SUBOPT_SYNCHRONOUS_COMMIT))
221  errorConflictingDefElem(defel, pstate);
222 
223  opts->specified_opts |= SUBOPT_SYNCHRONOUS_COMMIT;
224  opts->synchronous_commit = defGetString(defel);
225 
226  /* Test if the given value is valid for synchronous_commit GUC. */
227  (void) set_config_option("synchronous_commit", opts->synchronous_commit,
229  false, 0, false);
230  }
231  else if (IsSet(supported_opts, SUBOPT_REFRESH) &&
232  strcmp(defel->defname, "refresh") == 0)
233  {
234  if (IsSet(opts->specified_opts, SUBOPT_REFRESH))
235  errorConflictingDefElem(defel, pstate);
236 
237  opts->specified_opts |= SUBOPT_REFRESH;
238  opts->refresh = defGetBoolean(defel);
239  }
240  else if (IsSet(supported_opts, SUBOPT_BINARY) &&
241  strcmp(defel->defname, "binary") == 0)
242  {
243  if (IsSet(opts->specified_opts, SUBOPT_BINARY))
244  errorConflictingDefElem(defel, pstate);
245 
246  opts->specified_opts |= SUBOPT_BINARY;
247  opts->binary = defGetBoolean(defel);
248  }
249  else if (IsSet(supported_opts, SUBOPT_STREAMING) &&
250  strcmp(defel->defname, "streaming") == 0)
251  {
252  if (IsSet(opts->specified_opts, SUBOPT_STREAMING))
253  errorConflictingDefElem(defel, pstate);
254 
255  opts->specified_opts |= SUBOPT_STREAMING;
256  opts->streaming = defGetStreamingMode(defel);
257  }
258  else if (strcmp(defel->defname, "two_phase") == 0)
259  {
260  /*
261  * Do not allow toggling of two_phase option. Doing so could cause
262  * missing of transactions and lead to an inconsistent replica.
263  * See comments atop worker.c
264  *
265  * Note: Unsupported twophase indicates that this call originated
266  * from AlterSubscription.
267  */
268  if (!IsSet(supported_opts, SUBOPT_TWOPHASE_COMMIT))
269  ereport(ERROR,
270  (errcode(ERRCODE_SYNTAX_ERROR),
271  errmsg("unrecognized subscription parameter: \"%s\"", defel->defname)));
272 
273  if (IsSet(opts->specified_opts, SUBOPT_TWOPHASE_COMMIT))
274  errorConflictingDefElem(defel, pstate);
275 
276  opts->specified_opts |= SUBOPT_TWOPHASE_COMMIT;
277  opts->twophase = defGetBoolean(defel);
278  }
279  else if (IsSet(supported_opts, SUBOPT_DISABLE_ON_ERR) &&
280  strcmp(defel->defname, "disable_on_error") == 0)
281  {
282  if (IsSet(opts->specified_opts, SUBOPT_DISABLE_ON_ERR))
283  errorConflictingDefElem(defel, pstate);
284 
285  opts->specified_opts |= SUBOPT_DISABLE_ON_ERR;
286  opts->disableonerr = defGetBoolean(defel);
287  }
288  else if (IsSet(supported_opts, SUBOPT_PASSWORD_REQUIRED) &&
289  strcmp(defel->defname, "password_required") == 0)
290  {
291  if (IsSet(opts->specified_opts, SUBOPT_PASSWORD_REQUIRED))
292  errorConflictingDefElem(defel, pstate);
293 
294  opts->specified_opts |= SUBOPT_PASSWORD_REQUIRED;
295  opts->passwordrequired = defGetBoolean(defel);
296  }
297  else if (IsSet(supported_opts, SUBOPT_RUN_AS_OWNER) &&
298  strcmp(defel->defname, "run_as_owner") == 0)
299  {
300  if (IsSet(opts->specified_opts, SUBOPT_RUN_AS_OWNER))
301  errorConflictingDefElem(defel, pstate);
302 
303  opts->specified_opts |= SUBOPT_RUN_AS_OWNER;
304  opts->runasowner = defGetBoolean(defel);
305  }
306  else if (IsSet(supported_opts, SUBOPT_ORIGIN) &&
307  strcmp(defel->defname, "origin") == 0)
308  {
309  if (IsSet(opts->specified_opts, SUBOPT_ORIGIN))
310  errorConflictingDefElem(defel, pstate);
311 
312  opts->specified_opts |= SUBOPT_ORIGIN;
313  pfree(opts->origin);
314 
315  /*
316  * Even though the "origin" parameter allows only "none" and "any"
317  * values, it is implemented as a string type so that the
318  * parameter can be extended in future versions to support
319  * filtering using origin names specified by the user.
320  */
321  opts->origin = defGetString(defel);
322 
323  if ((pg_strcasecmp(opts->origin, LOGICALREP_ORIGIN_NONE) != 0) &&
324  (pg_strcasecmp(opts->origin, LOGICALREP_ORIGIN_ANY) != 0))
325  ereport(ERROR,
326  errcode(ERRCODE_INVALID_PARAMETER_VALUE),
327  errmsg("unrecognized origin value: \"%s\"", opts->origin));
328  }
329  else if (IsSet(supported_opts, SUBOPT_LSN) &&
330  strcmp(defel->defname, "lsn") == 0)
331  {
332  char *lsn_str = defGetString(defel);
333  XLogRecPtr lsn;
334 
335  if (IsSet(opts->specified_opts, SUBOPT_LSN))
336  errorConflictingDefElem(defel, pstate);
337 
338  /* Setting lsn = NONE is treated as resetting LSN */
339  if (strcmp(lsn_str, "none") == 0)
340  lsn = InvalidXLogRecPtr;
341  else
342  {
343  /* Parse the argument as LSN */
345  CStringGetDatum(lsn_str)));
346 
347  if (XLogRecPtrIsInvalid(lsn))
348  ereport(ERROR,
349  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
350  errmsg("invalid WAL location (LSN): %s", lsn_str)));
351  }
352 
353  opts->specified_opts |= SUBOPT_LSN;
354  opts->lsn = lsn;
355  }
356  else
357  ereport(ERROR,
358  (errcode(ERRCODE_SYNTAX_ERROR),
359  errmsg("unrecognized subscription parameter: \"%s\"", defel->defname)));
360  }
361 
362  /*
363  * We've been explicitly asked to not connect, that requires some
364  * additional processing.
365  */
366  if (!opts->connect && IsSet(supported_opts, SUBOPT_CONNECT))
367  {
368  /* Check for incompatible options from the user. */
369  if (opts->enabled &&
370  IsSet(opts->specified_opts, SUBOPT_ENABLED))
371  ereport(ERROR,
372  (errcode(ERRCODE_SYNTAX_ERROR),
373  /*- translator: both %s are strings of the form "option = value" */
374  errmsg("%s and %s are mutually exclusive options",
375  "connect = false", "enabled = true")));
376 
377  if (opts->create_slot &&
378  IsSet(opts->specified_opts, SUBOPT_CREATE_SLOT))
379  ereport(ERROR,
380  (errcode(ERRCODE_SYNTAX_ERROR),
381  errmsg("%s and %s are mutually exclusive options",
382  "connect = false", "create_slot = true")));
383 
384  if (opts->copy_data &&
385  IsSet(opts->specified_opts, SUBOPT_COPY_DATA))
386  ereport(ERROR,
387  (errcode(ERRCODE_SYNTAX_ERROR),
388  errmsg("%s and %s are mutually exclusive options",
389  "connect = false", "copy_data = true")));
390 
391  /* Change the defaults of other options. */
392  opts->enabled = false;
393  opts->create_slot = false;
394  opts->copy_data = false;
395  }
396 
397  /*
398  * Do additional checking for disallowed combination when slot_name = NONE
399  * was used.
400  */
401  if (!opts->slot_name &&
402  IsSet(opts->specified_opts, SUBOPT_SLOT_NAME))
403  {
404  if (opts->enabled)
405  {
406  if (IsSet(opts->specified_opts, SUBOPT_ENABLED))
407  ereport(ERROR,
408  (errcode(ERRCODE_SYNTAX_ERROR),
409  /*- translator: both %s are strings of the form "option = value" */
410  errmsg("%s and %s are mutually exclusive options",
411  "slot_name = NONE", "enabled = true")));
412  else
413  ereport(ERROR,
414  (errcode(ERRCODE_SYNTAX_ERROR),
415  /*- translator: both %s are strings of the form "option = value" */
416  errmsg("subscription with %s must also set %s",
417  "slot_name = NONE", "enabled = false")));
418  }
419 
420  if (opts->create_slot)
421  {
422  if (IsSet(opts->specified_opts, SUBOPT_CREATE_SLOT))
423  ereport(ERROR,
424  (errcode(ERRCODE_SYNTAX_ERROR),
425  /*- translator: both %s are strings of the form "option = value" */
426  errmsg("%s and %s are mutually exclusive options",
427  "slot_name = NONE", "create_slot = true")));
428  else
429  ereport(ERROR,
430  (errcode(ERRCODE_SYNTAX_ERROR),
431  /*- translator: both %s are strings of the form "option = value" */
432  errmsg("subscription with %s must also set %s",
433  "slot_name = NONE", "create_slot = false")));
434  }
435  }
436 }
bool defGetBoolean(DefElem *def)
Definition: define.c:108
void errorConflictingDefElem(DefElem *defel, ParseState *pstate)
Definition: define.c:385
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:3284
@ GUC_ACTION_SET
Definition: guc.h:197
@ PGC_S_TEST
Definition: guc.h:121
@ PGC_BACKEND
Definition: guc.h:73
Datum pg_lsn_in(PG_FUNCTION_ARGS)
Definition: pg_lsn.c:64
static XLogRecPtr DatumGetLSN(Datum X)
Definition: pg_lsn.h:22
#define LOGICALREP_ORIGIN_ANY
bool ReplicationSlotValidateName(const char *name, int elevel)
Definition: slot.c:199
char defGetStreamingMode(DefElem *def)

References Assert(), CStringGetDatum(), DatumGetLSN(), defGetBoolean(), defGetStreamingMode(), defGetString(), DefElem::defname, DirectFunctionCall1, ereport, errcode(), errmsg(), ERROR, errorConflictingDefElem(), GUC_ACTION_SET, InvalidXLogRecPtr, IsSet, lfirst, LOGICALREP_ORIGIN_ANY, LOGICALREP_ORIGIN_NONE, LOGICALREP_STREAM_OFF, opts, pfree(), pg_lsn_in(), pg_strcasecmp(), PGC_BACKEND, PGC_S_TEST, pstrdup(), ReplicationSlotValidateName(), set_config_option(), SUBOPT_BINARY, SUBOPT_CONNECT, SUBOPT_COPY_DATA, SUBOPT_CREATE_SLOT, SUBOPT_DISABLE_ON_ERR, SUBOPT_ENABLED, SUBOPT_LSN, SUBOPT_ORIGIN, SUBOPT_PASSWORD_REQUIRED, SUBOPT_REFRESH, SUBOPT_RUN_AS_OWNER, 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 537 of file subscriptioncmds.c.

538 {
539  ArrayType *arr;
540  Datum *datums;
541  MemoryContext memcxt;
542  MemoryContext oldcxt;
543 
544  /* Create memory context for temporary allocations. */
546  "publicationListToArray to array",
548  oldcxt = MemoryContextSwitchTo(memcxt);
549 
550  datums = (Datum *) palloc(sizeof(Datum) * list_length(publist));
551 
552  check_duplicates_in_publist(publist, datums);
553 
554  MemoryContextSwitchTo(oldcxt);
555 
556  arr = construct_array_builtin(datums, list_length(publist), TEXTOID);
557 
558  MemoryContextDelete(memcxt);
559 
560  return PointerGetDatum(arr);
561 }
ArrayType * construct_array_builtin(Datum *elems, int nelems, Oid elmtype)
Definition: arrayfuncs.c:3340
MemoryContext CurrentMemoryContext
Definition: mcxt.c:135
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:403
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:153
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:138
static Datum PointerGetDatum(const void *X)
Definition: postgres.h:322

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, check_duplicates_in_publist(), construct_array_builtin(), 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 1761 of file subscriptioncmds.c.

1762 {
1763  StringInfoData cmd;
1764 
1765  Assert(wrconn);
1766 
1767  load_file("libpqwalreceiver", false);
1768 
1769  initStringInfo(&cmd);
1770  appendStringInfo(&cmd, "DROP_REPLICATION_SLOT %s WAIT", quote_identifier(slotname));
1771 
1772  PG_TRY();
1773  {
1775 
1776  res = walrcv_exec(wrconn, cmd.data, 0, NULL);
1777 
1778  if (res->status == WALRCV_OK_COMMAND)
1779  {
1780  /* NOTICE. Success. */
1781  ereport(NOTICE,
1782  (errmsg("dropped replication slot \"%s\" on publisher",
1783  slotname)));
1784  }
1785  else if (res->status == WALRCV_ERROR &&
1786  missing_ok &&
1787  res->sqlstate == ERRCODE_UNDEFINED_OBJECT)
1788  {
1789  /* LOG. Error, but missing_ok = true. */
1790  ereport(LOG,
1791  (errmsg("could not drop replication slot \"%s\" on publisher: %s",
1792  slotname, res->err)));
1793  }
1794  else
1795  {
1796  /* ERROR. */
1797  ereport(ERROR,
1798  (errcode(ERRCODE_CONNECTION_FAILURE),
1799  errmsg("could not drop replication slot \"%s\" on publisher: %s",
1800  slotname, res->err)));
1801  }
1802 
1804  }
1805  PG_FINALLY();
1806  {
1807  pfree(cmd.data);
1808  }
1809  PG_END_TRY();
1810 }
#define LOG
Definition: elog.h:31
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:11965
@ WALRCV_OK_COMMAND
Definition: walreceiver.h:205
@ WALRCV_ERROR
Definition: walreceiver.h:204

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 2162 of file subscriptioncmds.c.

2163 {
2164  ListCell *lc;
2165 
2166  foreach(lc, rstates)
2167  {
2169  Oid relid = rstate->relid;
2170 
2171  /* Only cleanup resources of tablesync workers */
2172  if (!OidIsValid(relid))
2173  continue;
2174 
2175  /*
2176  * Caller needs to ensure that relstate doesn't change underneath us.
2177  * See DropSubscription where we get the relstates.
2178  */
2179  if (rstate->state != SUBREL_STATE_SYNCDONE)
2180  {
2181  char syncslotname[NAMEDATALEN] = {0};
2182 
2183  ReplicationSlotNameForTablesync(subid, relid, syncslotname,
2184  sizeof(syncslotname));
2185  elog(WARNING, "could not drop tablesync replication slot \"%s\"",
2186  syncslotname);
2187  }
2188  }
2189 
2190  ereport(ERROR,
2191  (errcode(ERRCODE_CONNECTION_FAILURE),
2192  errmsg("could not connect to publisher when attempting to drop replication slot \"%s\": %s",
2193  slotname, err),
2194  /* translator: %s is an SQL ALTER command */
2195  errhint("Use %s to disable the subscription, and then use %s to disassociate it from the slot.",
2196  "ALTER SUBSCRIPTION ... DISABLE",
2197  "ALTER SUBSCRIPTION ... SET (slot_name = NONE)")));
2198 }

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

Referenced by DropSubscription().