PostgreSQL Source Code  git master
subscriptioncmds.h File Reference
Include dependency graph for subscriptioncmds.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Functions

ObjectAddress CreateSubscription (ParseState *pstate, CreateSubscriptionStmt *stmt, bool isTopLevel)
 
ObjectAddress AlterSubscription (ParseState *pstate, AlterSubscriptionStmt *stmt, bool isTopLevel)
 
void DropSubscription (DropSubscriptionStmt *stmt, bool isTopLevel)
 
ObjectAddress AlterSubscriptionOwner (const char *name, Oid newOwnerId)
 
void AlterSubscriptionOwner_oid (Oid subid, Oid newOwnerId)
 

Function Documentation

◆ AlterSubscription()

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

Definition at line 815 of file subscriptioncmds.c.

817 {
818  Relation rel;
819  ObjectAddress myself;
820  bool nulls[Natts_pg_subscription];
821  bool replaces[Natts_pg_subscription];
822  Datum values[Natts_pg_subscription];
823  HeapTuple tup;
824  Oid subid;
825  bool update_tuple = false;
826  Subscription *sub;
828  bits32 supported_opts;
829  SubOpts opts = {0};
830 
831  rel = table_open(SubscriptionRelationId, RowExclusiveLock);
832 
833  /* Fetch the existing tuple. */
835  CStringGetDatum(stmt->subname));
836 
837  if (!HeapTupleIsValid(tup))
838  ereport(ERROR,
839  (errcode(ERRCODE_UNDEFINED_OBJECT),
840  errmsg("subscription \"%s\" does not exist",
841  stmt->subname)));
842 
843  form = (Form_pg_subscription) GETSTRUCT(tup);
844  subid = form->oid;
845 
846  /* must be owner */
847  if (!pg_subscription_ownercheck(subid, GetUserId()))
849  stmt->subname);
850 
851  sub = GetSubscription(subid, false);
852 
853  /* Lock the subscription so nobody else can do anything with it. */
854  LockSharedObject(SubscriptionRelationId, subid, 0, AccessExclusiveLock);
855 
856  /* Form a new tuple. */
857  memset(values, 0, sizeof(values));
858  memset(nulls, false, sizeof(nulls));
859  memset(replaces, false, sizeof(replaces));
860 
861  switch (stmt->kind)
862  {
864  {
865  supported_opts = (SUBOPT_SLOT_NAME |
868 
869  parse_subscription_options(pstate, stmt->options,
870  supported_opts, &opts);
871 
872  if (IsSet(opts.specified_opts, SUBOPT_SLOT_NAME))
873  {
874  /*
875  * The subscription must be disabled to allow slot_name as
876  * 'none', otherwise, the apply worker will repeatedly try
877  * to stream the data using that slot_name which neither
878  * exists on the publisher nor the user will be allowed to
879  * create it.
880  */
881  if (sub->enabled && !opts.slot_name)
882  ereport(ERROR,
883  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
884  errmsg("cannot set %s for enabled subscription",
885  "slot_name = NONE")));
886 
887  if (opts.slot_name)
888  values[Anum_pg_subscription_subslotname - 1] =
890  else
891  nulls[Anum_pg_subscription_subslotname - 1] = true;
892  replaces[Anum_pg_subscription_subslotname - 1] = true;
893  }
894 
895  if (opts.synchronous_commit)
896  {
897  values[Anum_pg_subscription_subsynccommit - 1] =
898  CStringGetTextDatum(opts.synchronous_commit);
899  replaces[Anum_pg_subscription_subsynccommit - 1] = true;
900  }
901 
902  if (IsSet(opts.specified_opts, SUBOPT_BINARY))
903  {
904  values[Anum_pg_subscription_subbinary - 1] =
905  BoolGetDatum(opts.binary);
906  replaces[Anum_pg_subscription_subbinary - 1] = true;
907  }
908 
909  if (IsSet(opts.specified_opts, SUBOPT_STREAMING))
910  {
911  values[Anum_pg_subscription_substream - 1] =
912  BoolGetDatum(opts.streaming);
913  replaces[Anum_pg_subscription_substream - 1] = true;
914  }
915 
916  update_tuple = true;
917  break;
918  }
919 
921  {
922  parse_subscription_options(pstate, stmt->options,
923  SUBOPT_ENABLED, &opts);
924  Assert(IsSet(opts.specified_opts, SUBOPT_ENABLED));
925 
926  if (!sub->slotname && opts.enabled)
927  ereport(ERROR,
928  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
929  errmsg("cannot enable subscription that does not have a slot name")));
930 
931  values[Anum_pg_subscription_subenabled - 1] =
932  BoolGetDatum(opts.enabled);
933  replaces[Anum_pg_subscription_subenabled - 1] = true;
934 
935  if (opts.enabled)
937 
938  update_tuple = true;
939  break;
940  }
941 
943  /* Load the library providing us libpq calls. */
944  load_file("libpqwalreceiver", false);
945  /* Check the connection info string. */
947 
948  values[Anum_pg_subscription_subconninfo - 1] =
950  replaces[Anum_pg_subscription_subconninfo - 1] = true;
951  update_tuple = true;
952  break;
953 
955  {
956  supported_opts = SUBOPT_COPY_DATA | SUBOPT_REFRESH;
957  parse_subscription_options(pstate, stmt->options,
958  supported_opts, &opts);
959 
960  values[Anum_pg_subscription_subpublications - 1] =
962  replaces[Anum_pg_subscription_subpublications - 1] = true;
963 
964  update_tuple = true;
965 
966  /* Refresh if user asked us to. */
967  if (opts.refresh)
968  {
969  if (!sub->enabled)
970  ereport(ERROR,
971  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
972  errmsg("ALTER SUBSCRIPTION with refresh is not allowed for disabled subscriptions"),
973  errhint("Use ALTER SUBSCRIPTION ... SET PUBLICATION ... WITH (refresh = false).")));
974 
975  /*
976  * See ALTER_SUBSCRIPTION_REFRESH for details why this is
977  * not allowed.
978  */
979  if (sub->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED && opts.copy_data)
980  ereport(ERROR,
981  (errcode(ERRCODE_SYNTAX_ERROR),
982  errmsg("ALTER SUBSCRIPTION with refresh and copy_data is not allowed when two_phase is enabled"),
983  errhint("Use ALTER SUBSCRIPTION ...SET PUBLICATION with refresh = false, or with copy_data = false"
984  ", or use DROP/CREATE SUBSCRIPTION.")));
985 
986  PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION with refresh");
987 
988  /* Make sure refresh sees the new list of publications. */
989  sub->publications = stmt->publication;
990 
991  AlterSubscription_refresh(sub, opts.copy_data);
992  }
993 
994  break;
995  }
996 
999  {
1000  List *publist;
1001  bool isadd = stmt->kind == ALTER_SUBSCRIPTION_ADD_PUBLICATION;
1002 
1003  supported_opts = SUBOPT_REFRESH | SUBOPT_COPY_DATA;
1004  parse_subscription_options(pstate, stmt->options,
1005  supported_opts, &opts);
1006 
1007  publist = merge_publications(sub->publications, stmt->publication, isadd, stmt->subname);
1008  values[Anum_pg_subscription_subpublications - 1] =
1009  publicationListToArray(publist);
1010  replaces[Anum_pg_subscription_subpublications - 1] = true;
1011 
1012  update_tuple = true;
1013 
1014  /* Refresh if user asked us to. */
1015  if (opts.refresh)
1016  {
1017  if (!sub->enabled)
1018  ereport(ERROR,
1019  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1020  errmsg("ALTER SUBSCRIPTION with refresh is not allowed for disabled subscriptions"),
1021  errhint("Use ALTER SUBSCRIPTION ... SET PUBLICATION ... WITH (refresh = false).")));
1022 
1023  /*
1024  * See ALTER_SUBSCRIPTION_REFRESH for details why this is
1025  * not allowed.
1026  */
1027  if (sub->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED && opts.copy_data)
1028  ereport(ERROR,
1029  (errcode(ERRCODE_SYNTAX_ERROR),
1030  errmsg("ALTER SUBSCRIPTION with refresh and copy_data is not allowed when two_phase is enabled"),
1031  errhint("Use ALTER SUBSCRIPTION ...SET PUBLICATION with refresh = false, or with copy_data = false"
1032  ", or use DROP/CREATE SUBSCRIPTION.")));
1033 
1034  PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION with refresh");
1035 
1036  /* Refresh the new list of publications. */
1037  sub->publications = publist;
1038 
1039  AlterSubscription_refresh(sub, opts.copy_data);
1040  }
1041 
1042  break;
1043  }
1044 
1046  {
1047  if (!sub->enabled)
1048  ereport(ERROR,
1049  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1050  errmsg("ALTER SUBSCRIPTION ... REFRESH is not allowed for disabled subscriptions")));
1051 
1052  parse_subscription_options(pstate, stmt->options,
1054 
1055  /*
1056  * The subscription option "two_phase" requires that
1057  * replication has passed the initial table synchronization
1058  * phase before the two_phase becomes properly enabled.
1059  *
1060  * But, having reached this two-phase commit "enabled" state
1061  * we must not allow any subsequent table initialization to
1062  * occur. So the ALTER SUBSCRIPTION ... REFRESH is disallowed
1063  * when the user had requested two_phase = on mode.
1064  *
1065  * The exception to this restriction is when copy_data =
1066  * false, because when copy_data is false the tablesync will
1067  * start already in READY state and will exit directly without
1068  * doing anything.
1069  *
1070  * For more details see comments atop worker.c.
1071  */
1072  if (sub->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED && opts.copy_data)
1073  ereport(ERROR,
1074  (errcode(ERRCODE_SYNTAX_ERROR),
1075  errmsg("ALTER SUBSCRIPTION ... REFRESH with copy_data is not allowed when two_phase is enabled"),
1076  errhint("Use ALTER SUBSCRIPTION ... REFRESH with copy_data = false"
1077  ", or use DROP/CREATE SUBSCRIPTION.")));
1078 
1079  PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION ... REFRESH");
1080 
1081  AlterSubscription_refresh(sub, opts.copy_data);
1082 
1083  break;
1084  }
1085 
1086  default:
1087  elog(ERROR, "unrecognized ALTER SUBSCRIPTION kind %d",
1088  stmt->kind);
1089  }
1090 
1091  /* Update the catalog if needed. */
1092  if (update_tuple)
1093  {
1094  tup = heap_modify_tuple(tup, RelationGetDescr(rel), values, nulls,
1095  replaces);
1096 
1097  CatalogTupleUpdate(rel, &tup->t_self, tup);
1098 
1099  heap_freetuple(tup);
1100  }
1101 
1103 
1104  ObjectAddressSet(myself, SubscriptionRelationId, subid);
1105 
1106  InvokeObjectPostAlterHook(SubscriptionRelationId, subid, 0);
1107 
1108  return myself;
1109 }
@ ACLCHECK_NOT_OWNER
Definition: acl.h:181
bool pg_subscription_ownercheck(Oid sub_oid, Oid roleid)
Definition: aclchk.c:5384
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3308
static Datum values[MAXATTR]
Definition: bootstrap.c:156
#define CStringGetTextDatum(s)
Definition: builtins.h:85
uint32 bits32
Definition: c.h:450
void load_file(const char *filename, bool restricted)
Definition: dfmgr.c:146
int errhint(const char *fmt,...)
Definition: elog.c:1151
int errcode(int sqlerrcode)
Definition: elog.c:693
int errmsg(const char *fmt,...)
Definition: elog.c:904
#define ERROR
Definition: elog.h:33
#define elog(elevel,...)
Definition: elog.h:218
#define ereport(elevel,...)
Definition: elog.h:143
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:631
Oid MyDatabaseId
Definition: globals.c:88
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:1113
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:649
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
void ApplyLauncherWakeupAtCommit(void)
Definition: launcher.c:785
Assert(fmt[strlen(fmt) - 1] !='\n')
void LockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:1018
#define AccessExclusiveLock
Definition: lockdefs.h:43
#define RowExclusiveLock
Definition: lockdefs.h:38
Oid GetUserId(void)
Definition: miscinit.c:495
Datum namein(PG_FUNCTION_ARGS)
Definition: name.c:48
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:175
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
@ ALTER_SUBSCRIPTION_ENABLED
Definition: parsenodes.h:3719
@ ALTER_SUBSCRIPTION_DROP_PUBLICATION
Definition: parsenodes.h:3717
@ ALTER_SUBSCRIPTION_SET_PUBLICATION
Definition: parsenodes.h:3715
@ ALTER_SUBSCRIPTION_REFRESH
Definition: parsenodes.h:3718
@ ALTER_SUBSCRIPTION_OPTIONS
Definition: parsenodes.h:3713
@ ALTER_SUBSCRIPTION_CONNECTION
Definition: parsenodes.h:3714
@ ALTER_SUBSCRIPTION_ADD_PUBLICATION
Definition: parsenodes.h:3716
@ OBJECT_SUBSCRIPTION
Definition: parsenodes.h:1826
static AmcheckOptions opts
Definition: pg_amcheck.c:110
Subscription * GetSubscription(Oid subid, bool missing_ok)
#define LOGICALREP_TWOPHASE_STATE_ENABLED
FormData_pg_subscription * Form_pg_subscription
#define CStringGetDatum(X)
Definition: postgres.h:622
uintptr_t Datum
Definition: postgres.h:411
#define BoolGetDatum(X)
Definition: postgres.h:446
unsigned int Oid
Definition: postgres_ext.h:31
#define RelationGetDescr(relation)
Definition: rel.h:504
AlterSubscriptionType kind
Definition: parsenodes.h:3725
ItemPointerData t_self
Definition: htup.h:65
Definition: pg_list.h:51
#define SUBOPT_STREAMING
#define SUBOPT_SYNCHRONOUS_COMMIT
#define SUBOPT_ENABLED
static Datum publicationListToArray(List *publist)
static void parse_subscription_options(ParseState *pstate, List *stmt_options, bits32 supported_opts, SubOpts *opts)
#define SUBOPT_SLOT_NAME
#define SUBOPT_COPY_DATA
static void AlterSubscription_refresh(Subscription *sub, bool copy_data)
static List * merge_publications(List *oldpublist, List *newpublist, bool addpub, const char *subname)
#define SUBOPT_BINARY
#define IsSet(val, bits)
#define SUBOPT_REFRESH
#define SearchSysCacheCopy2(cacheId, key1, key2)
Definition: syscache.h:179
@ SUBSCRIPTIONNAME
Definition: syscache.h:96
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define walrcv_check_conninfo(conninfo)
Definition: walreceiver.h:406
void PreventInTransactionBlock(bool isTopLevel, const char *stmtType)
Definition: xact.c:3450

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

Referenced by ProcessUtilitySlow().

◆ AlterSubscriptionOwner()

ObjectAddress AlterSubscriptionOwner ( const char *  name,
Oid  newOwnerId 
)

Definition at line 1492 of file subscriptioncmds.c.

1493 {
1494  Oid subid;
1495  HeapTuple tup;
1496  Relation rel;
1497  ObjectAddress address;
1498  Form_pg_subscription form;
1499 
1500  rel = table_open(SubscriptionRelationId, RowExclusiveLock);
1501 
1504 
1505  if (!HeapTupleIsValid(tup))
1506  ereport(ERROR,
1507  (errcode(ERRCODE_UNDEFINED_OBJECT),
1508  errmsg("subscription \"%s\" does not exist", name)));
1509 
1510  form = (Form_pg_subscription) GETSTRUCT(tup);
1511  subid = form->oid;
1512 
1513  AlterSubscriptionOwner_internal(rel, tup, newOwnerId);
1514 
1515  ObjectAddressSet(address, SubscriptionRelationId, subid);
1516 
1517  heap_freetuple(tup);
1518 
1520 
1521  return address;
1522 }
const char * name
Definition: encode.c:561
static void AlterSubscriptionOwner_internal(Relation rel, HeapTuple tup, Oid newOwnerId)

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

Referenced by ExecAlterOwnerStmt().

◆ AlterSubscriptionOwner_oid()

void AlterSubscriptionOwner_oid ( Oid  subid,
Oid  newOwnerId 
)

Definition at line 1528 of file subscriptioncmds.c.

1529 {
1530  HeapTuple tup;
1531  Relation rel;
1532 
1533  rel = table_open(SubscriptionRelationId, RowExclusiveLock);
1534 
1536 
1537  if (!HeapTupleIsValid(tup))
1538  ereport(ERROR,
1539  (errcode(ERRCODE_UNDEFINED_OBJECT),
1540  errmsg("subscription with OID %u does not exist", subid)));
1541 
1542  AlterSubscriptionOwner_internal(rel, tup, newOwnerId);
1543 
1544  heap_freetuple(tup);
1545 
1547 }
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:177
@ SUBSCRIPTIONOID
Definition: syscache.h:97

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

Referenced by shdepReassignOwned().

◆ CreateSubscription()

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

Definition at line 369 of file subscriptioncmds.c.

371 {
372  Relation rel;
373  ObjectAddress myself;
374  Oid subid;
375  bool nulls[Natts_pg_subscription];
376  Datum values[Natts_pg_subscription];
377  Oid owner = GetUserId();
378  HeapTuple tup;
379  char *conninfo;
380  char originname[NAMEDATALEN];
381  List *publications;
382  bits32 supported_opts;
383  SubOpts opts = {0};
384 
385  /*
386  * Parse and check options.
387  *
388  * Connection and publication should not be specified here.
389  */
390  supported_opts = (SUBOPT_CONNECT | SUBOPT_ENABLED | SUBOPT_CREATE_SLOT |
394  parse_subscription_options(pstate, stmt->options, supported_opts, &opts);
395 
396  /*
397  * Since creating a replication slot is not transactional, rolling back
398  * the transaction leaves the created replication slot. So we cannot run
399  * CREATE SUBSCRIPTION inside a transaction block if creating a
400  * replication slot.
401  */
402  if (opts.create_slot)
403  PreventInTransactionBlock(isTopLevel, "CREATE SUBSCRIPTION ... WITH (create_slot = true)");
404 
405  if (!superuser())
406  ereport(ERROR,
407  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
408  errmsg("must be superuser to create subscriptions")));
409 
410  /*
411  * If built with appropriate switch, whine when regression-testing
412  * conventions for subscription names are violated.
413  */
414 #ifdef ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS
415  if (strncmp(stmt->subname, "regress_", 8) != 0)
416  elog(WARNING, "subscriptions created by regression test cases should have names starting with \"regress_\"");
417 #endif
418 
419  rel = table_open(SubscriptionRelationId, RowExclusiveLock);
420 
421  /* Check if name is used */
422  subid = GetSysCacheOid2(SUBSCRIPTIONNAME, Anum_pg_subscription_oid,
424  if (OidIsValid(subid))
425  {
426  ereport(ERROR,
428  errmsg("subscription \"%s\" already exists",
429  stmt->subname)));
430  }
431 
432  if (!IsSet(opts.specified_opts, SUBOPT_SLOT_NAME) &&
433  opts.slot_name == NULL)
434  opts.slot_name = stmt->subname;
435 
436  /* The default for synchronous_commit of subscriptions is off. */
437  if (opts.synchronous_commit == NULL)
438  opts.synchronous_commit = "off";
439 
440  conninfo = stmt->conninfo;
441  publications = stmt->publication;
442 
443  /* Load the library providing us libpq calls. */
444  load_file("libpqwalreceiver", false);
445 
446  /* Check the connection info string. */
447  walrcv_check_conninfo(conninfo);
448 
449  /* Everything ok, form a new tuple. */
450  memset(values, 0, sizeof(values));
451  memset(nulls, false, sizeof(nulls));
452 
453  subid = GetNewOidWithIndex(rel, SubscriptionObjectIndexId,
454  Anum_pg_subscription_oid);
455  values[Anum_pg_subscription_oid - 1] = ObjectIdGetDatum(subid);
456  values[Anum_pg_subscription_subdbid - 1] = ObjectIdGetDatum(MyDatabaseId);
457  values[Anum_pg_subscription_subname - 1] =
459  values[Anum_pg_subscription_subowner - 1] = ObjectIdGetDatum(owner);
460  values[Anum_pg_subscription_subenabled - 1] = BoolGetDatum(opts.enabled);
461  values[Anum_pg_subscription_subbinary - 1] = BoolGetDatum(opts.binary);
462  values[Anum_pg_subscription_substream - 1] = BoolGetDatum(opts.streaming);
463  values[Anum_pg_subscription_subtwophasestate - 1] =
464  CharGetDatum(opts.twophase ?
467  values[Anum_pg_subscription_subconninfo - 1] =
468  CStringGetTextDatum(conninfo);
469  if (opts.slot_name)
470  values[Anum_pg_subscription_subslotname - 1] =
472  else
473  nulls[Anum_pg_subscription_subslotname - 1] = true;
474  values[Anum_pg_subscription_subsynccommit - 1] =
475  CStringGetTextDatum(opts.synchronous_commit);
476  values[Anum_pg_subscription_subpublications - 1] =
477  publicationListToArray(publications);
478 
479  tup = heap_form_tuple(RelationGetDescr(rel), values, nulls);
480 
481  /* Insert tuple into catalog. */
482  CatalogTupleInsert(rel, tup);
483  heap_freetuple(tup);
484 
485  recordDependencyOnOwner(SubscriptionRelationId, subid, owner);
486 
487  snprintf(originname, sizeof(originname), "pg_%u", subid);
488  replorigin_create(originname);
489 
490  /*
491  * Connect to remote side to execute requested commands and fetch table
492  * info.
493  */
494  if (opts.connect)
495  {
496  char *err;
498  List *tables;
499  ListCell *lc;
500  char table_state;
501 
502  /* Try to connect to the publisher. */
503  wrconn = walrcv_connect(conninfo, true, stmt->subname, &err);
504  if (!wrconn)
505  ereport(ERROR,
506  (errcode(ERRCODE_CONNECTION_FAILURE),
507  errmsg("could not connect to the publisher: %s", err)));
508 
509  PG_TRY();
510  {
511  /*
512  * Set sync state based on if we were asked to do data copy or
513  * not.
514  */
515  table_state = opts.copy_data ? SUBREL_STATE_INIT : SUBREL_STATE_READY;
516 
517  /*
518  * Get the table list from publisher and build local table status
519  * info.
520  */
521  tables = fetch_table_list(wrconn, publications);
522  foreach(lc, tables)
523  {
524  RangeVar *rv = (RangeVar *) lfirst(lc);
525  Oid relid;
526 
527  relid = RangeVarGetRelid(rv, AccessShareLock, false);
528 
529  /* Check for supported relkind. */
531  rv->schemaname, rv->relname);
532 
533  AddSubscriptionRelState(subid, relid, table_state,
535  }
536 
537  /*
538  * If requested, create permanent slot for the subscription. We
539  * won't use the initial snapshot for anything, so no need to
540  * export it.
541  */
542  if (opts.create_slot)
543  {
544  bool twophase_enabled = false;
545 
546  Assert(opts.slot_name);
547 
548  /*
549  * Even if two_phase is set, don't create the slot with
550  * two-phase enabled. Will enable it once all the tables are
551  * synced and ready. This avoids race-conditions like prepared
552  * transactions being skipped due to changes not being applied
553  * due to checks in should_apply_changes_for_rel() when
554  * tablesync for the corresponding tables are in progress. See
555  * comments atop worker.c.
556  *
557  * Note that if tables were specified but copy_data is false
558  * then it is safe to enable two_phase up-front because those
559  * tables are already initially in READY state. When the
560  * subscription has no tables, we leave the twophase state as
561  * PENDING, to allow ALTER SUBSCRIPTION ... REFRESH
562  * PUBLICATION to work.
563  */
564  if (opts.twophase && !opts.copy_data && tables != NIL)
565  twophase_enabled = true;
566 
567  walrcv_create_slot(wrconn, opts.slot_name, false, twophase_enabled,
568  CRS_NOEXPORT_SNAPSHOT, NULL);
569 
570  if (twophase_enabled)
572 
573  ereport(NOTICE,
574  (errmsg("created replication slot \"%s\" on publisher",
575  opts.slot_name)));
576  }
577  }
578  PG_FINALLY();
579  {
581  }
582  PG_END_TRY();
583  }
584  else
586  /* translator: %s is an SQL ALTER statement */
587  (errmsg("tables were not subscribed, you will have to run %s to subscribe the tables",
588  "ALTER SUBSCRIPTION ... REFRESH PUBLICATION")));
589 
591 
592  if (opts.enabled)
594 
595  ObjectAddressSet(myself, SubscriptionRelationId, subid);
596 
597  InvokeObjectPostCreateHook(SubscriptionRelationId, subid, 0);
598 
599  return myself;
600 }
#define OidIsValid(objectId)
Definition: c.h:710
Oid GetNewOidWithIndex(Relation relation, Oid indexId, AttrNumber oidcolumn)
Definition: catalog.c:381
#define PG_END_TRY()
Definition: elog.h:324
#define PG_TRY()
Definition: elog.h:299
#define WARNING
Definition: elog.h:30
#define PG_FINALLY()
Definition: elog.h:316
#define NOTICE
Definition: elog.h:29
void CheckSubscriptionRelkind(char relkind, const char *nspname, const char *relname)
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:221
#define AccessShareLock
Definition: lockdefs.h:36
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1974
#define RangeVarGetRelid(relation, lockmode, missing_ok)
Definition: namespace.h:79
#define InvokeObjectPostCreateHook(classId, objectId, subId)
Definition: objectaccess.h:151
RepOriginId replorigin_create(const char *roname)
Definition: origin.c:240
#define NAMEDATALEN
#define lfirst(lc)
Definition: pg_list.h:169
#define NIL
Definition: pg_list.h:65
void recordDependencyOnOwner(Oid classId, Oid objectId, Oid owner)
Definition: pg_shdepend.c:164
void AddSubscriptionRelState(Oid subid, Oid relid, char state, XLogRecPtr sublsn)
#define LOGICALREP_TWOPHASE_STATE_DISABLED
#define LOGICALREP_TWOPHASE_STATE_PENDING
#define snprintf
Definition: port.h:225
#define CharGetDatum(X)
Definition: postgres.h:460
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:32
char * relname
Definition: primnodes.h:68
char * schemaname
Definition: primnodes.h:67
#define SUBOPT_CREATE_SLOT
#define SUBOPT_TWOPHASE_COMMIT
static List * fetch_table_list(WalReceiverConn *wrconn, List *publications)
#define SUBOPT_CONNECT
bool superuser(void)
Definition: superuser.c:46
#define GetSysCacheOid2(cacheId, oidcol, key1, key2)
Definition: syscache.h:197
void UpdateTwoPhaseState(Oid suboid, char new_state)
Definition: tablesync.c:1283
static WalReceiverConn * wrconn
Definition: walreceiver.c:94
#define walrcv_create_slot(conn, slotname, temporary, two_phase, snapshot_action, lsn)
Definition: walreceiver.h:426
#define walrcv_connect(conninfo, logical, appname, err)
Definition: walreceiver.h:404
#define walrcv_disconnect(conn)
Definition: walreceiver.h:432
@ CRS_NOEXPORT_SNAPSHOT
Definition: walsender.h:23
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28

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

Referenced by ProcessUtilitySlow().

◆ DropSubscription()

void DropSubscription ( DropSubscriptionStmt stmt,
bool  isTopLevel 
)

Definition at line 1115 of file subscriptioncmds.c.

1116 {
1117  Relation rel;
1118  ObjectAddress myself;
1119  HeapTuple tup;
1120  Oid subid;
1121  Datum datum;
1122  bool isnull;
1123  char *subname;
1124  char *conninfo;
1125  char *slotname;
1126  List *subworkers;
1127  ListCell *lc;
1128  char originname[NAMEDATALEN];
1129  char *err = NULL;
1131  Form_pg_subscription form;
1132  List *rstates;
1133 
1134  /*
1135  * Lock pg_subscription with AccessExclusiveLock to ensure that the
1136  * launcher doesn't restart new worker during dropping the subscription
1137  */
1138  rel = table_open(SubscriptionRelationId, AccessExclusiveLock);
1139 
1141  CStringGetDatum(stmt->subname));
1142 
1143  if (!HeapTupleIsValid(tup))
1144  {
1145  table_close(rel, NoLock);
1146 
1147  if (!stmt->missing_ok)
1148  ereport(ERROR,
1149  (errcode(ERRCODE_UNDEFINED_OBJECT),
1150  errmsg("subscription \"%s\" does not exist",
1151  stmt->subname)));
1152  else
1153  ereport(NOTICE,
1154  (errmsg("subscription \"%s\" does not exist, skipping",
1155  stmt->subname)));
1156 
1157  return;
1158  }
1159 
1160  form = (Form_pg_subscription) GETSTRUCT(tup);
1161  subid = form->oid;
1162 
1163  /* must be owner */
1164  if (!pg_subscription_ownercheck(subid, GetUserId()))
1166  stmt->subname);
1167 
1168  /* DROP hook for the subscription being removed */
1169  InvokeObjectDropHook(SubscriptionRelationId, subid, 0);
1170 
1171  /*
1172  * Lock the subscription so nobody else can do anything with it (including
1173  * the replication workers).
1174  */
1175  LockSharedObject(SubscriptionRelationId, subid, 0, AccessExclusiveLock);
1176 
1177  /* Get subname */
1178  datum = SysCacheGetAttr(SUBSCRIPTIONOID, tup,
1179  Anum_pg_subscription_subname, &isnull);
1180  Assert(!isnull);
1181  subname = pstrdup(NameStr(*DatumGetName(datum)));
1182 
1183  /* Get conninfo */
1184  datum = SysCacheGetAttr(SUBSCRIPTIONOID, tup,
1185  Anum_pg_subscription_subconninfo, &isnull);
1186  Assert(!isnull);
1187  conninfo = TextDatumGetCString(datum);
1188 
1189  /* Get slotname */
1190  datum = SysCacheGetAttr(SUBSCRIPTIONOID, tup,
1191  Anum_pg_subscription_subslotname, &isnull);
1192  if (!isnull)
1193  slotname = pstrdup(NameStr(*DatumGetName(datum)));
1194  else
1195  slotname = NULL;
1196 
1197  /*
1198  * Since dropping a replication slot is not transactional, the replication
1199  * slot stays dropped even if the transaction rolls back. So we cannot
1200  * run DROP SUBSCRIPTION inside a transaction block if dropping the
1201  * replication slot. Also, in this case, we report a message for dropping
1202  * the subscription to the stats collector.
1203  *
1204  * XXX The command name should really be something like "DROP SUBSCRIPTION
1205  * of a subscription that is associated with a replication slot", but we
1206  * don't have the proper facilities for that.
1207  */
1208  if (slotname)
1209  PreventInTransactionBlock(isTopLevel, "DROP SUBSCRIPTION");
1210 
1211  ObjectAddressSet(myself, SubscriptionRelationId, subid);
1212  EventTriggerSQLDropAddObject(&myself, true, true);
1213 
1214  /* Remove the tuple from catalog. */
1215  CatalogTupleDelete(rel, &tup->t_self);
1216 
1217  ReleaseSysCache(tup);
1218 
1219  /*
1220  * Stop all the subscription workers immediately.
1221  *
1222  * This is necessary if we are dropping the replication slot, so that the
1223  * slot becomes accessible.
1224  *
1225  * It is also necessary if the subscription is disabled and was disabled
1226  * in the same transaction. Then the workers haven't seen the disabling
1227  * yet and will still be running, leading to hangs later when we want to
1228  * drop the replication origin. If the subscription was disabled before
1229  * this transaction, then there shouldn't be any workers left, so this
1230  * won't make a difference.
1231  *
1232  * New workers won't be started because we hold an exclusive lock on the
1233  * subscription till the end of the transaction.
1234  */
1235  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
1236  subworkers = logicalrep_workers_find(subid, false);
1237  LWLockRelease(LogicalRepWorkerLock);
1238  foreach(lc, subworkers)
1239  {
1241 
1243  }
1244  list_free(subworkers);
1245 
1246  /*
1247  * Cleanup of tablesync replication origins.
1248  *
1249  * Any READY-state relations would already have dealt with clean-ups.
1250  *
1251  * Note that the state can't change because we have already stopped both
1252  * the apply and tablesync workers and they can't restart because of
1253  * exclusive lock on the subscription.
1254  */
1255  rstates = GetSubscriptionNotReadyRelations(subid);
1256  foreach(lc, rstates)
1257  {
1259  Oid relid = rstate->relid;
1260 
1261  /* Only cleanup resources of tablesync workers */
1262  if (!OidIsValid(relid))
1263  continue;
1264 
1265  /*
1266  * Drop the tablesync's origin tracking if exists.
1267  *
1268  * It is possible that the origin is not yet created for tablesync
1269  * worker so passing missing_ok = true. This can happen for the states
1270  * before SUBREL_STATE_FINISHEDCOPY.
1271  */
1272  ReplicationOriginNameForTablesync(subid, relid, originname,
1273  sizeof(originname));
1274  replorigin_drop_by_name(originname, true, false);
1275  }
1276 
1277  /* Clean up dependencies */
1278  deleteSharedDependencyRecordsFor(SubscriptionRelationId, subid, 0);
1279 
1280  /* Remove any associated relation synchronization states. */
1282 
1283  /* Remove the origin tracking if exists. */
1284  snprintf(originname, sizeof(originname), "pg_%u", subid);
1285  replorigin_drop_by_name(originname, true, false);
1286 
1287  /*
1288  * If there is no slot associated with the subscription, we can finish
1289  * here.
1290  */
1291  if (!slotname && rstates == NIL)
1292  {
1293  table_close(rel, NoLock);
1294  return;
1295  }
1296 
1297  /*
1298  * Try to acquire the connection necessary for dropping slots.
1299  *
1300  * Note: If the slotname is NONE/NULL then we allow the command to finish
1301  * and users need to manually cleanup the apply and tablesync worker slots
1302  * later.
1303  *
1304  * This has to be at the end because otherwise if there is an error while
1305  * doing the database operations we won't be able to rollback dropped
1306  * slot.
1307  */
1308  load_file("libpqwalreceiver", false);
1309 
1310  wrconn = walrcv_connect(conninfo, true, subname, &err);
1311  if (wrconn == NULL)
1312  {
1313  if (!slotname)
1314  {
1315  /* be tidy */
1316  list_free(rstates);
1317  table_close(rel, NoLock);
1318  return;
1319  }
1320  else
1321  {
1322  ReportSlotConnectionError(rstates, subid, slotname, err);
1323  }
1324  }
1325 
1326  PG_TRY();
1327  {
1328  foreach(lc, rstates)
1329  {
1331  Oid relid = rstate->relid;
1332 
1333  /* Only cleanup resources of tablesync workers */
1334  if (!OidIsValid(relid))
1335  continue;
1336 
1337  /*
1338  * Drop the tablesync slots associated with removed tables.
1339  *
1340  * For SYNCDONE/READY states, the tablesync slot is known to have
1341  * already been dropped by the tablesync worker.
1342  *
1343  * For other states, there is no certainty, maybe the slot does
1344  * not exist yet. Also, if we fail after removing some of the
1345  * slots, next time, it will again try to drop already dropped
1346  * slots and fail. For these reasons, we allow missing_ok = true
1347  * for the drop.
1348  */
1349  if (rstate->state != SUBREL_STATE_SYNCDONE)
1350  {
1351  char syncslotname[NAMEDATALEN] = {0};
1352 
1353  ReplicationSlotNameForTablesync(subid, relid, syncslotname,
1354  sizeof(syncslotname));
1355  ReplicationSlotDropAtPubNode(wrconn, syncslotname, true);
1356  }
1357  }
1358 
1359  list_free(rstates);
1360 
1361  /*
1362  * If there is a slot associated with the subscription, then drop the
1363  * replication slot at the publisher.
1364  */
1365  if (slotname)
1366  ReplicationSlotDropAtPubNode(wrconn, slotname, false);
1367 
1368  }
1369  PG_FINALLY();
1370  {
1372  }
1373  PG_END_TRY();
1374 
1375  /*
1376  * Send a message for dropping this subscription to the stats collector.
1377  * We can safely report dropping the subscription statistics here if the
1378  * subscription is associated with a replication slot since we cannot run
1379  * DROP SUBSCRIPTION inside a transaction block. Subscription statistics
1380  * will be removed later by (auto)vacuum either if it's not associated
1381  * with a replication slot or if the message for dropping the subscription
1382  * gets lost.
1383  */
1384  if (slotname)
1386 
1387  table_close(rel, NoLock);
1388 }
#define TextDatumGetCString(d)
Definition: builtins.h:86
#define NameStr(name)
Definition: c.h:681
void EventTriggerSQLDropAddObject(const ObjectAddress *object, bool original, bool normal)
void CatalogTupleDelete(Relation heapRel, ItemPointer tid)
Definition: indexing.c:350
List * logicalrep_workers_find(Oid subid, bool only_running)
Definition: launcher.c:243
void logicalrep_worker_stop(Oid subid, Oid relid)
Definition: launcher.c:437
void list_free(List *list)
Definition: list.c:1505
#define NoLock
Definition: lockdefs.h:34
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1199
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
@ LW_SHARED
Definition: lwlock.h:105
char * pstrdup(const char *in)
Definition: mcxt.c:1299
#define InvokeObjectDropHook(classId, objectId, subId)
Definition: objectaccess.h:160
void replorigin_drop_by_name(const char *name, bool missing_ok, bool nowait)
Definition: origin.c:414
void deleteSharedDependencyRecordsFor(Oid classId, Oid objectId, int32 objectSubId)
Definition: pg_shdepend.c:1001
List * GetSubscriptionNotReadyRelations(Oid subid)
void RemoveSubscriptionRel(Oid subid, Oid relid)
NameData subname
void pgstat_report_subscription_drop(Oid subid)
Definition: pgstat.c:1980
#define DatumGetName(X)
Definition: postgres.h:629
#define InvalidOid
Definition: postgres_ext.h:36
static void ReportSlotConnectionError(List *rstates, Oid subid, char *slotname, char *err)
void ReplicationSlotDropAtPubNode(WalReceiverConn *wrconn, char *slotname, bool missing_ok)
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1198
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1411
HeapTuple SearchSysCache2(int cacheId, Datum key1, Datum key2)
Definition: syscache.c:1161
void ReplicationOriginNameForTablesync(Oid suboid, Oid relid, char *originname, int szorgname)
Definition: tablesync.c:907
void ReplicationSlotNameForTablesync(Oid suboid, Oid relid, char *syncslotname, int szslot)
Definition: tablesync.c:894

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

Referenced by ProcessUtilitySlow().