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 (CreateSubscriptionStmt *stmt, bool isTopLevel)
 
ObjectAddress AlterSubscription (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 ( AlterSubscriptionStmt stmt,
bool  isTopLevel 
)

Definition at line 753 of file subscriptioncmds.c.

References AccessExclusiveLock, aclcheck_error(), ACLCHECK_NOT_OWNER, ALTER_SUBSCRIPTION_ADD_PUBLICATION, ALTER_SUBSCRIPTION_CONNECTION, ALTER_SUBSCRIPTION_DROP_PUBLICATION, ALTER_SUBSCRIPTION_ENABLED, ALTER_SUBSCRIPTION_OPTIONS, ALTER_SUBSCRIPTION_REFRESH, ALTER_SUBSCRIPTION_SET_PUBLICATION, AlterSubscription_refresh(), ApplyLauncherWakeupAtCommit(), Assert, 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, AlterSubscriptionStmt::kind, load_file(), LockSharedObject(), merge_publications(), MyDatabaseId, namein(), OBJECT_SUBSCRIPTION, ObjectAddressSet, AlterSubscriptionStmt::options, parse_subscription_options(), pg_subscription_ownercheck(), PreventInTransactionBlock(), AlterSubscriptionStmt::publication, publicationListToArray(), Subscription::publications, RelationGetDescr, RowExclusiveLock, SearchSysCacheCopy2, Subscription::slotname, AlterSubscriptionStmt::subname, SUBSCRIPTIONNAME, synchronous_commit, HeapTupleData::t_self, table_close(), table_open(), values, and walrcv_check_conninfo.

Referenced by ProcessUtilitySlow().

754 {
755  Relation rel;
756  ObjectAddress myself;
757  bool nulls[Natts_pg_subscription];
758  bool replaces[Natts_pg_subscription];
759  Datum values[Natts_pg_subscription];
760  HeapTuple tup;
761  Oid subid;
762  bool update_tuple = false;
763  Subscription *sub;
765 
766  rel = table_open(SubscriptionRelationId, RowExclusiveLock);
767 
768  /* Fetch the existing tuple. */
770  CStringGetDatum(stmt->subname));
771 
772  if (!HeapTupleIsValid(tup))
773  ereport(ERROR,
774  (errcode(ERRCODE_UNDEFINED_OBJECT),
775  errmsg("subscription \"%s\" does not exist",
776  stmt->subname)));
777 
778  form = (Form_pg_subscription) GETSTRUCT(tup);
779  subid = form->oid;
780 
781  /* must be owner */
782  if (!pg_subscription_ownercheck(subid, GetUserId()))
784  stmt->subname);
785 
786  sub = GetSubscription(subid, false);
787 
788  /* Lock the subscription so nobody else can do anything with it. */
789  LockSharedObject(SubscriptionRelationId, subid, 0, AccessExclusiveLock);
790 
791  /* Form a new tuple. */
792  memset(values, 0, sizeof(values));
793  memset(nulls, false, sizeof(nulls));
794  memset(replaces, false, sizeof(replaces));
795 
796  switch (stmt->kind)
797  {
799  {
800  char *slotname;
801  bool slotname_given;
802  char *synchronous_commit;
803  bool binary_given;
804  bool binary;
805  bool streaming_given;
806  bool streaming;
807 
809  NULL, /* no "connect" */
810  NULL, NULL, /* no "enabled" */
811  NULL, /* no "create_slot" */
812  &slotname_given, &slotname,
813  NULL, /* no "copy_data" */
814  &synchronous_commit,
815  NULL, /* no "refresh" */
816  &binary_given, &binary,
817  &streaming_given, &streaming);
818 
819  if (slotname_given)
820  {
821  if (sub->enabled && !slotname)
822  ereport(ERROR,
823  (errcode(ERRCODE_SYNTAX_ERROR),
824  errmsg("cannot set %s for enabled subscription",
825  "slot_name = NONE")));
826 
827  if (slotname)
828  values[Anum_pg_subscription_subslotname - 1] =
830  else
831  nulls[Anum_pg_subscription_subslotname - 1] = true;
832  replaces[Anum_pg_subscription_subslotname - 1] = true;
833  }
834 
835  if (synchronous_commit)
836  {
837  values[Anum_pg_subscription_subsynccommit - 1] =
838  CStringGetTextDatum(synchronous_commit);
839  replaces[Anum_pg_subscription_subsynccommit - 1] = true;
840  }
841 
842  if (binary_given)
843  {
844  values[Anum_pg_subscription_subbinary - 1] =
845  BoolGetDatum(binary);
846  replaces[Anum_pg_subscription_subbinary - 1] = true;
847  }
848 
849  if (streaming_given)
850  {
851  values[Anum_pg_subscription_substream - 1] =
852  BoolGetDatum(streaming);
853  replaces[Anum_pg_subscription_substream - 1] = true;
854  }
855 
856  update_tuple = true;
857  break;
858  }
859 
861  {
862  bool enabled,
863  enabled_given;
864 
866  NULL, /* no "connect" */
867  &enabled_given, &enabled,
868  NULL, /* no "create_slot" */
869  NULL, NULL, /* no "slot_name" */
870  NULL, /* no "copy_data" */
871  NULL, /* no "synchronous_commit" */
872  NULL, /* no "refresh" */
873  NULL, NULL, /* no "binary" */
874  NULL, NULL); /* no streaming */
875  Assert(enabled_given);
876 
877  if (!sub->slotname && enabled)
878  ereport(ERROR,
879  (errcode(ERRCODE_SYNTAX_ERROR),
880  errmsg("cannot enable subscription that does not have a slot name")));
881 
882  values[Anum_pg_subscription_subenabled - 1] =
883  BoolGetDatum(enabled);
884  replaces[Anum_pg_subscription_subenabled - 1] = true;
885 
886  if (enabled)
888 
889  update_tuple = true;
890  break;
891  }
892 
894  /* Load the library providing us libpq calls. */
895  load_file("libpqwalreceiver", false);
896  /* Check the connection info string. */
898 
899  values[Anum_pg_subscription_subconninfo - 1] =
901  replaces[Anum_pg_subscription_subconninfo - 1] = true;
902  update_tuple = true;
903  break;
904 
906  {
907  bool copy_data;
908  bool refresh;
909 
911  NULL, /* no "connect" */
912  NULL, NULL, /* no "enabled" */
913  NULL, /* no "create_slot" */
914  NULL, NULL, /* no "slot_name" */
915  &copy_data,
916  NULL, /* no "synchronous_commit" */
917  &refresh,
918  NULL, NULL, /* no "binary" */
919  NULL, NULL); /* no "streaming" */
920  values[Anum_pg_subscription_subpublications - 1] =
922  replaces[Anum_pg_subscription_subpublications - 1] = true;
923 
924  update_tuple = true;
925 
926  /* Refresh if user asked us to. */
927  if (refresh)
928  {
929  if (!sub->enabled)
930  ereport(ERROR,
931  (errcode(ERRCODE_SYNTAX_ERROR),
932  errmsg("ALTER SUBSCRIPTION with refresh is not allowed for disabled subscriptions"),
933  errhint("Use ALTER SUBSCRIPTION ... SET PUBLICATION ... WITH (refresh = false).")));
934 
935  PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION with refresh");
936 
937  /* Make sure refresh sees the new list of publications. */
938  sub->publications = stmt->publication;
939 
940  AlterSubscription_refresh(sub, copy_data);
941  }
942 
943  break;
944  }
945 
948  {
949  bool isadd = stmt->kind == ALTER_SUBSCRIPTION_ADD_PUBLICATION;
950  bool copy_data;
951  bool refresh;
952  List *publist;
953 
954  publist = merge_publications(sub->publications, stmt->publication, isadd, stmt->subname);
955 
957  NULL, /* no "connect" */
958  NULL, NULL, /* no "enabled" */
959  NULL, /* no "create_slot" */
960  NULL, NULL, /* no "slot_name" */
961  isadd ? &copy_data : NULL, /* for drop, no
962  * "copy_data" */
963  NULL, /* no "synchronous_commit" */
964  &refresh,
965  NULL, NULL, /* no "binary" */
966  NULL, NULL); /* no "streaming" */
967 
968  values[Anum_pg_subscription_subpublications - 1] =
969  publicationListToArray(publist);
970  replaces[Anum_pg_subscription_subpublications - 1] = true;
971 
972  update_tuple = true;
973 
974  /* Refresh if user asked us to. */
975  if (refresh)
976  {
977  if (!sub->enabled)
978  ereport(ERROR,
979  (errcode(ERRCODE_SYNTAX_ERROR),
980  errmsg("ALTER SUBSCRIPTION with refresh is not allowed for disabled subscriptions"),
981  errhint("Use ALTER SUBSCRIPTION ... SET PUBLICATION ... WITH (refresh = false).")));
982 
983  PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION with refresh");
984 
985  /* Only refresh the added/dropped list of publications. */
986  sub->publications = stmt->publication;
987 
988  AlterSubscription_refresh(sub, copy_data);
989  }
990 
991  break;
992  }
993 
995  {
996  bool copy_data;
997 
998  if (!sub->enabled)
999  ereport(ERROR,
1000  (errcode(ERRCODE_SYNTAX_ERROR),
1001  errmsg("ALTER SUBSCRIPTION ... REFRESH is not allowed for disabled subscriptions")));
1002 
1004  NULL, /* no "connect" */
1005  NULL, NULL, /* no "enabled" */
1006  NULL, /* no "create_slot" */
1007  NULL, NULL, /* no "slot_name" */
1008  &copy_data,
1009  NULL, /* no "synchronous_commit" */
1010  NULL, /* no "refresh" */
1011  NULL, NULL, /* no "binary" */
1012  NULL, NULL); /* no "streaming" */
1013 
1014  PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION ... REFRESH");
1015 
1016  AlterSubscription_refresh(sub, copy_data);
1017 
1018  break;
1019  }
1020 
1021  default:
1022  elog(ERROR, "unrecognized ALTER SUBSCRIPTION kind %d",
1023  stmt->kind);
1024  }
1025 
1026  /* Update the catalog if needed. */
1027  if (update_tuple)
1028  {
1029  tup = heap_modify_tuple(tup, RelationGetDescr(rel), values, nulls,
1030  replaces);
1031 
1032  CatalogTupleUpdate(rel, &tup->t_self, tup);
1033 
1034  heap_freetuple(tup);
1035  }
1036 
1038 
1039  ObjectAddressSet(myself, SubscriptionRelationId, subid);
1040 
1041  InvokeObjectPostAlterHook(SubscriptionRelationId, subid, 0);
1042 
1043  return myself;
1044 }
Datum namein(PG_FUNCTION_ARGS)
Definition: name.c:48
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
int errhint(const char *fmt,...)
Definition: elog.c:1156
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
#define RelationGetDescr(relation)
Definition: rel.h:495
Oid GetUserId(void)
Definition: miscinit.c:478
#define walrcv_check_conninfo(conninfo)
Definition: walreceiver.h:403
int errcode(int sqlerrcode)
Definition: elog.c:698
static Datum publicationListToArray(List *publist)
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:626
FormData_pg_subscription * Form_pg_subscription
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
Subscription * GetSubscription(Oid subid, bool missing_ok)
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3313
#define ERROR
Definition: elog.h:46
ItemPointerData t_self
Definition: htup.h:65
static void parse_subscription_options(List *options, bool *connect, bool *enabled_given, bool *enabled, bool *create_slot, bool *slot_name_given, char **slot_name, bool *copy_data, char **synchronous_commit, bool *refresh, bool *binary_given, bool *binary, bool *streaming_given, bool *streaming)
AlterSubscriptionType kind
Definition: parsenodes.h:3654
#define RowExclusiveLock
Definition: lockdefs.h:38
#define CStringGetDatum(X)
Definition: postgres.h:622
void PreventInTransactionBlock(bool isTopLevel, const char *stmtType)
Definition: xact.c:3379
List * publications
int synchronous_commit
Definition: xact.c:83
#define InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:175
uintptr_t Datum
Definition: postgres.h:411
Oid MyDatabaseId
Definition: globals.c:88
void LockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:1017
#define BoolGetDatum(X)
Definition: postgres.h:446
#define ereport(elevel,...)
Definition: elog.h:157
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:804
void load_file(const char *filename, bool restricted)
Definition: dfmgr.c:146
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
static Datum values[MAXATTR]
Definition: bootstrap.c:166
#define AccessExclusiveLock
Definition: lockdefs.h:45
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define elog(elevel,...)
Definition: elog.h:232
#define CStringGetTextDatum(s)
Definition: builtins.h:82
void ApplyLauncherWakeupAtCommit(void)
Definition: launcher.c:780
#define SearchSysCacheCopy2(cacheId, key1, key2)
Definition: syscache.h:177
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:1113
Definition: pg_list.h:50
static void AlterSubscription_refresh(Subscription *sub, bool copy_data)
static List * merge_publications(List *oldpublist, List *newpublist, bool addpub, const char *subname)
bool pg_subscription_ownercheck(Oid sub_oid, Oid roleid)
Definition: aclchk.c:5387

◆ AlterSubscriptionOwner()

ObjectAddress AlterSubscriptionOwner ( const char *  name,
Oid  newOwnerId 
)

Definition at line 1411 of file subscriptioncmds.c.

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

Referenced by ExecAlterOwnerStmt().

1412 {
1413  Oid subid;
1414  HeapTuple tup;
1415  Relation rel;
1416  ObjectAddress address;
1417  Form_pg_subscription form;
1418 
1419  rel = table_open(SubscriptionRelationId, RowExclusiveLock);
1420 
1423 
1424  if (!HeapTupleIsValid(tup))
1425  ereport(ERROR,
1426  (errcode(ERRCODE_UNDEFINED_OBJECT),
1427  errmsg("subscription \"%s\" does not exist", name)));
1428 
1429  form = (Form_pg_subscription) GETSTRUCT(tup);
1430  subid = form->oid;
1431 
1432  AlterSubscriptionOwner_internal(rel, tup, newOwnerId);
1433 
1434  ObjectAddressSet(address, SubscriptionRelationId, subid);
1435 
1436  heap_freetuple(tup);
1437 
1439 
1440  return address;
1441 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
int errcode(int sqlerrcode)
Definition: elog.c:698
FormData_pg_subscription * Form_pg_subscription
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
#define ERROR
Definition: elog.h:46
#define RowExclusiveLock
Definition: lockdefs.h:38
#define CStringGetDatum(X)
Definition: postgres.h:622
Oid MyDatabaseId
Definition: globals.c:88
#define ereport(elevel,...)
Definition: elog.h:157
static void AlterSubscriptionOwner_internal(Relation rel, HeapTuple tup, Oid newOwnerId)
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
const char * name
Definition: encode.c:515
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define SearchSysCacheCopy2(cacheId, key1, key2)
Definition: syscache.h:177
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39

◆ AlterSubscriptionOwner_oid()

void AlterSubscriptionOwner_oid ( Oid  subid,
Oid  newOwnerId 
)

Definition at line 1447 of file subscriptioncmds.c.

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

Referenced by shdepReassignOwned().

1448 {
1449  HeapTuple tup;
1450  Relation rel;
1451 
1452  rel = table_open(SubscriptionRelationId, RowExclusiveLock);
1453 
1455 
1456  if (!HeapTupleIsValid(tup))
1457  ereport(ERROR,
1458  (errcode(ERRCODE_UNDEFINED_OBJECT),
1459  errmsg("subscription with OID %u does not exist", subid)));
1460 
1461  AlterSubscriptionOwner_internal(rel, tup, newOwnerId);
1462 
1463  heap_freetuple(tup);
1464 
1466 }
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
int errcode(int sqlerrcode)
Definition: elog.c:698
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
#define RowExclusiveLock
Definition: lockdefs.h:38
#define ereport(elevel,...)
Definition: elog.h:157
static void AlterSubscriptionOwner_internal(Relation rel, HeapTuple tup, Oid newOwnerId)
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:175
int errmsg(const char *fmt,...)
Definition: elog.c:909
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39

◆ CreateSubscription()

ObjectAddress CreateSubscription ( CreateSubscriptionStmt stmt,
bool  isTopLevel 
)

Definition at line 325 of file subscriptioncmds.c.

References AccessShareLock, AddSubscriptionRelState(), ApplyLauncherWakeupAtCommit(), Assert, BoolGetDatum, CatalogTupleInsert(), CheckSubscriptionRelkind(), connect, CreateSubscriptionStmt::conninfo, create_slot, 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, lfirst, load_file(), MyDatabaseId, NAMEDATALEN, namein(), NOTICE, ObjectAddressSet, ObjectIdGetDatum, OidIsValid, CreateSubscriptionStmt::options, 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, SUBSCRIPTIONNAME, SubscriptionObjectIndexId, superuser(), synchronous_commit, table_close(), table_open(), values, walrcv_check_conninfo, walrcv_connect, walrcv_create_slot, walrcv_disconnect, WARNING, and wrconn.

Referenced by ProcessUtilitySlow().

326 {
327  Relation rel;
328  ObjectAddress myself;
329  Oid subid;
330  bool nulls[Natts_pg_subscription];
331  Datum values[Natts_pg_subscription];
332  Oid owner = GetUserId();
333  HeapTuple tup;
334  bool connect;
335  bool enabled_given;
336  bool enabled;
337  bool copy_data;
338  bool streaming;
339  bool streaming_given;
340  char *synchronous_commit;
341  char *conninfo;
342  char *slotname;
343  bool slotname_given;
344  bool binary;
345  bool binary_given;
346  char originname[NAMEDATALEN];
347  bool create_slot;
348  List *publications;
349 
350  /*
351  * Parse and check options.
352  *
353  * Connection and publication should not be specified here.
354  */
356  &connect,
357  &enabled_given, &enabled,
358  &create_slot,
359  &slotname_given, &slotname,
360  &copy_data,
361  &synchronous_commit,
362  NULL, /* no "refresh" */
363  &binary_given, &binary,
364  &streaming_given, &streaming);
365 
366  /*
367  * Since creating a replication slot is not transactional, rolling back
368  * the transaction leaves the created replication slot. So we cannot run
369  * CREATE SUBSCRIPTION inside a transaction block if creating a
370  * replication slot.
371  */
372  if (create_slot)
373  PreventInTransactionBlock(isTopLevel, "CREATE SUBSCRIPTION ... WITH (create_slot = true)");
374 
375  if (!superuser())
376  ereport(ERROR,
377  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
378  errmsg("must be superuser to create subscriptions")));
379 
380  /*
381  * If built with appropriate switch, whine when regression-testing
382  * conventions for subscription names are violated.
383  */
384 #ifdef ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS
385  if (strncmp(stmt->subname, "regress_", 8) != 0)
386  elog(WARNING, "subscriptions created by regression test cases should have names starting with \"regress_\"");
387 #endif
388 
389  rel = table_open(SubscriptionRelationId, RowExclusiveLock);
390 
391  /* Check if name is used */
392  subid = GetSysCacheOid2(SUBSCRIPTIONNAME, Anum_pg_subscription_oid,
394  if (OidIsValid(subid))
395  {
396  ereport(ERROR,
398  errmsg("subscription \"%s\" already exists",
399  stmt->subname)));
400  }
401 
402  if (!slotname_given && slotname == NULL)
403  slotname = stmt->subname;
404 
405  /* The default for synchronous_commit of subscriptions is off. */
406  if (synchronous_commit == NULL)
407  synchronous_commit = "off";
408 
409  conninfo = stmt->conninfo;
410  publications = stmt->publication;
411 
412  /* Load the library providing us libpq calls. */
413  load_file("libpqwalreceiver", false);
414 
415  /* Check the connection info string. */
416  walrcv_check_conninfo(conninfo);
417 
418  /* Everything ok, form a new tuple. */
419  memset(values, 0, sizeof(values));
420  memset(nulls, false, sizeof(nulls));
421 
423  Anum_pg_subscription_oid);
424  values[Anum_pg_subscription_oid - 1] = ObjectIdGetDatum(subid);
425  values[Anum_pg_subscription_subdbid - 1] = ObjectIdGetDatum(MyDatabaseId);
426  values[Anum_pg_subscription_subname - 1] =
428  values[Anum_pg_subscription_subowner - 1] = ObjectIdGetDatum(owner);
429  values[Anum_pg_subscription_subenabled - 1] = BoolGetDatum(enabled);
430  values[Anum_pg_subscription_subbinary - 1] = BoolGetDatum(binary);
431  values[Anum_pg_subscription_substream - 1] = BoolGetDatum(streaming);
432  values[Anum_pg_subscription_subconninfo - 1] =
433  CStringGetTextDatum(conninfo);
434  if (slotname)
435  values[Anum_pg_subscription_subslotname - 1] =
437  else
438  nulls[Anum_pg_subscription_subslotname - 1] = true;
439  values[Anum_pg_subscription_subsynccommit - 1] =
440  CStringGetTextDatum(synchronous_commit);
441  values[Anum_pg_subscription_subpublications - 1] =
442  publicationListToArray(publications);
443 
444  tup = heap_form_tuple(RelationGetDescr(rel), values, nulls);
445 
446  /* Insert tuple into catalog. */
447  CatalogTupleInsert(rel, tup);
448  heap_freetuple(tup);
449 
450  recordDependencyOnOwner(SubscriptionRelationId, subid, owner);
451 
452  snprintf(originname, sizeof(originname), "pg_%u", subid);
453  replorigin_create(originname);
454 
455  /*
456  * Connect to remote side to execute requested commands and fetch table
457  * info.
458  */
459  if (connect)
460  {
461  char *err;
463  List *tables;
464  ListCell *lc;
465  char table_state;
466 
467  /* Try to connect to the publisher. */
468  wrconn = walrcv_connect(conninfo, true, stmt->subname, &err);
469  if (!wrconn)
470  ereport(ERROR,
471  (errmsg("could not connect to the publisher: %s", err)));
472 
473  PG_TRY();
474  {
475  /*
476  * Set sync state based on if we were asked to do data copy or
477  * not.
478  */
479  table_state = copy_data ? SUBREL_STATE_INIT : SUBREL_STATE_READY;
480 
481  /*
482  * Get the table list from publisher and build local table status
483  * info.
484  */
485  tables = fetch_table_list(wrconn, publications);
486  foreach(lc, tables)
487  {
488  RangeVar *rv = (RangeVar *) lfirst(lc);
489  Oid relid;
490 
491  relid = RangeVarGetRelid(rv, AccessShareLock, false);
492 
493  /* Check for supported relkind. */
495  rv->schemaname, rv->relname);
496 
497  AddSubscriptionRelState(subid, relid, table_state,
499  }
500 
501  /*
502  * If requested, create permanent slot for the subscription. We
503  * won't use the initial snapshot for anything, so no need to
504  * export it.
505  */
506  if (create_slot)
507  {
508  Assert(slotname);
509 
510  walrcv_create_slot(wrconn, slotname, false,
511  CRS_NOEXPORT_SNAPSHOT, NULL);
512  ereport(NOTICE,
513  (errmsg("created replication slot \"%s\" on publisher",
514  slotname)));
515  }
516  }
517  PG_FINALLY();
518  {
519  walrcv_disconnect(wrconn);
520  }
521  PG_END_TRY();
522  }
523  else
525  /* translator: %s is an SQL ALTER statement */
526  (errmsg("tables were not subscribed, you will have to run %s to subscribe the tables",
527  "ALTER SUBSCRIPTION ... REFRESH PUBLICATION")));
528 
530 
531  if (enabled)
533 
534  ObjectAddressSet(myself, SubscriptionRelationId, subid);
535 
536  InvokeObjectPostCreateHook(SubscriptionRelationId, subid, 0);
537 
538  return myself;
539 }
static List * fetch_table_list(WalReceiverConn *wrconn, List *publications)
Oid GetNewOidWithIndex(Relation relation, Oid indexId, AttrNumber oidcolumn)
Definition: catalog.c:322
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
Datum namein(PG_FUNCTION_ARGS)
Definition: name.c:48
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define InvokeObjectPostCreateHook(classId, objectId, subId)
Definition: objectaccess.h:151
#define RelationGetDescr(relation)
Definition: rel.h:495
Oid GetUserId(void)
Definition: miscinit.c:478
#define RangeVarGetRelid(relation, lockmode, missing_ok)
Definition: namespace.h:78
#define walrcv_check_conninfo(conninfo)
Definition: walreceiver.h:403
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1974
#define AccessShareLock
Definition: lockdefs.h:36
static bool create_slot
int errcode(int sqlerrcode)
Definition: elog.c:698
bool superuser(void)
Definition: superuser.c:46
static Datum publicationListToArray(List *publist)
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
#define connect(s, name, namelen)
Definition: win32_port.h:463
#define DirectFunctionCall1(func, arg1)
Definition: fmgr.h:626
void recordDependencyOnOwner(Oid classId, Oid objectId, Oid owner)
Definition: pg_shdepend.c:165
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
unsigned int Oid
Definition: postgres_ext.h:31
#define walrcv_create_slot(conn, slotname, temporary, snapshot_action, lsn)
Definition: walreceiver.h:423
#define OidIsValid(objectId)
Definition: c.h:710
static WalReceiverConn * wrconn
Definition: walreceiver.c:94
char * schemaname
Definition: primnodes.h:67
#define NAMEDATALEN
char * relname
Definition: primnodes.h:68
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
static void parse_subscription_options(List *options, bool *connect, bool *enabled_given, bool *enabled, bool *create_slot, bool *slot_name_given, char **slot_name, bool *copy_data, char **synchronous_commit, bool *refresh, bool *binary_given, bool *binary, bool *streaming_given, bool *streaming)
void AddSubscriptionRelState(Oid subid, Oid relid, char state, XLogRecPtr sublsn)
#define SubscriptionObjectIndexId
#define RowExclusiveLock
Definition: lockdefs.h:38
#define CStringGetDatum(X)
Definition: postgres.h:622
void PreventInTransactionBlock(bool isTopLevel, const char *stmtType)
Definition: xact.c:3379
void CheckSubscriptionRelkind(char relkind, const char *nspname, const char *relname)
RepOriginId replorigin_create(char *roname)
Definition: origin.c:240
int synchronous_commit
Definition: xact.c:83
#define WARNING
Definition: elog.h:40
#define PG_FINALLY()
Definition: elog.h:330
uintptr_t Datum
Definition: postgres.h:411
Oid MyDatabaseId
Definition: globals.c:88
#define BoolGetDatum(X)
Definition: postgres.h:446
#define ereport(elevel,...)
Definition: elog.h:157
#define NOTICE
Definition: elog.h:37
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
#define GetSysCacheOid2(cacheId, oidcol, key1, key2)
Definition: syscache.h:195
void load_file(const char *filename, bool restricted)
Definition: dfmgr.c:146
#define walrcv_disconnect(conn)
Definition: walreceiver.h:429
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
static Datum values[MAXATTR]
Definition: bootstrap.c:166
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define elog(elevel,...)
Definition: elog.h:232
#define CStringGetTextDatum(s)
Definition: builtins.h:82
void ApplyLauncherWakeupAtCommit(void)
Definition: launcher.c:780
#define PG_TRY()
Definition: elog.h:313
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:32
Definition: pg_list.h:50
#define snprintf
Definition: port.h:216
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:221
#define PG_END_TRY()
Definition: elog.h:338
#define walrcv_connect(conninfo, logical, appname, err)
Definition: walreceiver.h:401

◆ DropSubscription()

void DropSubscription ( DropSubscriptionStmt stmt,
bool  isTopLevel 
)

Definition at line 1050 of file subscriptioncmds.c.

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

Referenced by ProcessUtilitySlow().

1051 {
1052  Relation rel;
1053  ObjectAddress myself;
1054  HeapTuple tup;
1055  Oid subid;
1056  Datum datum;
1057  bool isnull;
1058  char *subname;
1059  char *conninfo;
1060  char *slotname;
1061  List *subworkers;
1062  ListCell *lc;
1063  char originname[NAMEDATALEN];
1064  char *err = NULL;
1066  Form_pg_subscription form;
1067  List *rstates;
1068 
1069  /*
1070  * Lock pg_subscription with AccessExclusiveLock to ensure that the
1071  * launcher doesn't restart new worker during dropping the subscription
1072  */
1073  rel = table_open(SubscriptionRelationId, AccessExclusiveLock);
1074 
1076  CStringGetDatum(stmt->subname));
1077 
1078  if (!HeapTupleIsValid(tup))
1079  {
1080  table_close(rel, NoLock);
1081 
1082  if (!stmt->missing_ok)
1083  ereport(ERROR,
1084  (errcode(ERRCODE_UNDEFINED_OBJECT),
1085  errmsg("subscription \"%s\" does not exist",
1086  stmt->subname)));
1087  else
1088  ereport(NOTICE,
1089  (errmsg("subscription \"%s\" does not exist, skipping",
1090  stmt->subname)));
1091 
1092  return;
1093  }
1094 
1095  form = (Form_pg_subscription) GETSTRUCT(tup);
1096  subid = form->oid;
1097 
1098  /* must be owner */
1099  if (!pg_subscription_ownercheck(subid, GetUserId()))
1101  stmt->subname);
1102 
1103  /* DROP hook for the subscription being removed */
1104  InvokeObjectDropHook(SubscriptionRelationId, subid, 0);
1105 
1106  /*
1107  * Lock the subscription so nobody else can do anything with it (including
1108  * the replication workers).
1109  */
1110  LockSharedObject(SubscriptionRelationId, subid, 0, AccessExclusiveLock);
1111 
1112  /* Get subname */
1113  datum = SysCacheGetAttr(SUBSCRIPTIONOID, tup,
1114  Anum_pg_subscription_subname, &isnull);
1115  Assert(!isnull);
1116  subname = pstrdup(NameStr(*DatumGetName(datum)));
1117 
1118  /* Get conninfo */
1119  datum = SysCacheGetAttr(SUBSCRIPTIONOID, tup,
1120  Anum_pg_subscription_subconninfo, &isnull);
1121  Assert(!isnull);
1122  conninfo = TextDatumGetCString(datum);
1123 
1124  /* Get slotname */
1125  datum = SysCacheGetAttr(SUBSCRIPTIONOID, tup,
1126  Anum_pg_subscription_subslotname, &isnull);
1127  if (!isnull)
1128  slotname = pstrdup(NameStr(*DatumGetName(datum)));
1129  else
1130  slotname = NULL;
1131 
1132  /*
1133  * Since dropping a replication slot is not transactional, the replication
1134  * slot stays dropped even if the transaction rolls back. So we cannot
1135  * run DROP SUBSCRIPTION inside a transaction block if dropping the
1136  * replication slot.
1137  *
1138  * XXX The command name should really be something like "DROP SUBSCRIPTION
1139  * of a subscription that is associated with a replication slot", but we
1140  * don't have the proper facilities for that.
1141  */
1142  if (slotname)
1143  PreventInTransactionBlock(isTopLevel, "DROP SUBSCRIPTION");
1144 
1145  ObjectAddressSet(myself, SubscriptionRelationId, subid);
1146  EventTriggerSQLDropAddObject(&myself, true, true);
1147 
1148  /* Remove the tuple from catalog. */
1149  CatalogTupleDelete(rel, &tup->t_self);
1150 
1151  ReleaseSysCache(tup);
1152 
1153  /*
1154  * Stop all the subscription workers immediately.
1155  *
1156  * This is necessary if we are dropping the replication slot, so that the
1157  * slot becomes accessible.
1158  *
1159  * It is also necessary if the subscription is disabled and was disabled
1160  * in the same transaction. Then the workers haven't seen the disabling
1161  * yet and will still be running, leading to hangs later when we want to
1162  * drop the replication origin. If the subscription was disabled before
1163  * this transaction, then there shouldn't be any workers left, so this
1164  * won't make a difference.
1165  *
1166  * New workers won't be started because we hold an exclusive lock on the
1167  * subscription till the end of the transaction.
1168  */
1169  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
1170  subworkers = logicalrep_workers_find(subid, false);
1171  LWLockRelease(LogicalRepWorkerLock);
1172  foreach(lc, subworkers)
1173  {
1175 
1177  }
1178  list_free(subworkers);
1179 
1180  /*
1181  * Cleanup of tablesync replication origins.
1182  *
1183  * Any READY-state relations would already have dealt with clean-ups.
1184  *
1185  * Note that the state can't change because we have already stopped both
1186  * the apply and tablesync workers and they can't restart because of
1187  * exclusive lock on the subscription.
1188  */
1189  rstates = GetSubscriptionNotReadyRelations(subid);
1190  foreach(lc, rstates)
1191  {
1193  Oid relid = rstate->relid;
1194 
1195  /* Only cleanup resources of tablesync workers */
1196  if (!OidIsValid(relid))
1197  continue;
1198 
1199  /*
1200  * Drop the tablesync's origin tracking if exists.
1201  *
1202  * It is possible that the origin is not yet created for tablesync
1203  * worker so passing missing_ok = true. This can happen for the states
1204  * before SUBREL_STATE_FINISHEDCOPY.
1205  */
1206  ReplicationOriginNameForTablesync(subid, relid, originname,
1207  sizeof(originname));
1208  replorigin_drop_by_name(originname, true, false);
1209  }
1210 
1211  /* Clean up dependencies */
1212  deleteSharedDependencyRecordsFor(SubscriptionRelationId, subid, 0);
1213 
1214  /* Remove any associated relation synchronization states. */
1216 
1217  /* Remove the origin tracking if exists. */
1218  snprintf(originname, sizeof(originname), "pg_%u", subid);
1219  replorigin_drop_by_name(originname, true, false);
1220 
1221  /*
1222  * If there is no slot associated with the subscription, we can finish
1223  * here.
1224  */
1225  if (!slotname && rstates == NIL)
1226  {
1227  table_close(rel, NoLock);
1228  return;
1229  }
1230 
1231  /*
1232  * Try to acquire the connection necessary for dropping slots.
1233  *
1234  * Note: If the slotname is NONE/NULL then we allow the command to finish
1235  * and users need to manually cleanup the apply and tablesync worker slots
1236  * later.
1237  *
1238  * This has to be at the end because otherwise if there is an error while
1239  * doing the database operations we won't be able to rollback dropped
1240  * slot.
1241  */
1242  load_file("libpqwalreceiver", false);
1243 
1244  wrconn = walrcv_connect(conninfo, true, subname, &err);
1245  if (wrconn == NULL)
1246  {
1247  if (!slotname)
1248  {
1249  /* be tidy */
1250  list_free(rstates);
1251  table_close(rel, NoLock);
1252  return;
1253  }
1254  else
1255  {
1256  ReportSlotConnectionError(rstates, subid, slotname, err);
1257  }
1258  }
1259 
1260  PG_TRY();
1261  {
1262  foreach(lc, rstates)
1263  {
1265  Oid relid = rstate->relid;
1266 
1267  /* Only cleanup resources of tablesync workers */
1268  if (!OidIsValid(relid))
1269  continue;
1270 
1271  /*
1272  * Drop the tablesync slots associated with removed tables.
1273  *
1274  * For SYNCDONE/READY states, the tablesync slot is known to have
1275  * already been dropped by the tablesync worker.
1276  *
1277  * For other states, there is no certainty, maybe the slot does
1278  * not exist yet. Also, if we fail after removing some of the
1279  * slots, next time, it will again try to drop already dropped
1280  * slots and fail. For these reasons, we allow missing_ok = true
1281  * for the drop.
1282  */
1283  if (rstate->state != SUBREL_STATE_SYNCDONE)
1284  {
1285  char syncslotname[NAMEDATALEN] = {0};
1286 
1287  ReplicationSlotNameForTablesync(subid, relid, syncslotname,
1288  sizeof(syncslotname));
1289  ReplicationSlotDropAtPubNode(wrconn, syncslotname, true);
1290  }
1291  }
1292 
1293  list_free(rstates);
1294 
1295  /*
1296  * If there is a slot associated with the subscription, then drop the
1297  * replication slot at the publisher.
1298  */
1299  if (slotname)
1300  ReplicationSlotDropAtPubNode(wrconn, slotname, false);
1301 
1302  }
1303  PG_FINALLY();
1304  {
1305  walrcv_disconnect(wrconn);
1306  }
1307  PG_END_TRY();
1308 
1309  table_close(rel, NoLock);
1310 }
#define NIL
Definition: pg_list.h:65
List * logicalrep_workers_find(Oid subid, bool only_running)
Definition: launcher.c:243
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
void RemoveSubscriptionRel(Oid subid, Oid relid)
void ReplicationSlotDropAtPubNode(WalReceiverConn *wrconn, char *slotname, bool missing_ok)
Oid GetUserId(void)
Definition: miscinit.c:478
void replorigin_drop_by_name(char *name, bool missing_ok, bool nowait)
Definition: origin.c:414
char * pstrdup(const char *in)
Definition: mcxt.c:1299
#define InvokeObjectDropHook(classId, objectId, subId)
Definition: objectaccess.h:160
static void ReportSlotConnectionError(List *rstates, Oid subid, char *slotname, char *err)
int errcode(int sqlerrcode)
Definition: elog.c:698
void CatalogTupleDelete(Relation heapRel, ItemPointer tid)
Definition: indexing.c:350
FormData_pg_subscription * Form_pg_subscription
unsigned int Oid
Definition: postgres_ext.h:31
NameData subname
#define OidIsValid(objectId)
Definition: c.h:710
static WalReceiverConn * wrconn
Definition: walreceiver.c:94
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1816
#define NAMEDATALEN
#define DatumGetName(X)
Definition: postgres.h:629
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:3313
#define ERROR
Definition: elog.h:46
ItemPointerData t_self
Definition: htup.h:65
#define NoLock
Definition: lockdefs.h:34
void logicalrep_worker_stop(Oid subid, Oid relid)
Definition: launcher.c:436
#define CStringGetDatum(X)
Definition: postgres.h:622
void PreventInTransactionBlock(bool isTopLevel, const char *stmtType)
Definition: xact.c:3379
void deleteSharedDependencyRecordsFor(Oid classId, Oid objectId, int32 objectSubId)
Definition: pg_shdepend.c:1001
#define PG_FINALLY()
Definition: elog.h:330
#define TextDatumGetCString(d)
Definition: builtins.h:83
uintptr_t Datum
Definition: postgres.h:411
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1175
Datum SysCacheGetAttr(int cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition: syscache.c:1388
Oid MyDatabaseId
Definition: globals.c:88
void LockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition: lmgr.c:1017
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:157
#define NOTICE
Definition: elog.h:37
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
void load_file(const char *filename, bool restricted)
Definition: dfmgr.c:146
void EventTriggerSQLDropAddObject(const ObjectAddress *object, bool original, bool normal)
HeapTuple SearchSysCache2(int cacheId, Datum key1, Datum key2)
Definition: syscache.c:1138
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1203
void ReplicationOriginNameForTablesync(Oid suboid, Oid relid, char *originname, int szorgname)
Definition: tablesync.c:904
#define walrcv_disconnect(conn)
Definition: walreceiver.h:429
#define ObjectAddressSet(addr, class_id, object_id)
Definition: objectaddress.h:40
#define AccessExclusiveLock
Definition: lockdefs.h:45
int errmsg(const char *fmt,...)
Definition: elog.c:909
void list_free(List *list)
Definition: list.c:1391
#define NameStr(name)
Definition: c.h:681
#define PG_TRY()
Definition: elog.h:313
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Definition: pg_list.h:50
List * GetSubscriptionNotReadyRelations(Oid subid)
#define snprintf
Definition: port.h:216
#define PG_END_TRY()
Definition: elog.h:338
void ReplicationSlotNameForTablesync(Oid suboid, Oid relid, char *syncslotname, int szslot)
Definition: tablesync.c:891
bool pg_subscription_ownercheck(Oid sub_oid, Oid roleid)
Definition: aclchk.c:5387
#define walrcv_connect(conninfo, logical, appname, err)
Definition: walreceiver.h:401