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

Go to the source code of this file.

Functions

static Listfetch_table_list (WalReceiverConn *wrconn, List *publications)
 
static void check_duplicates_in_publist (List *publist, Datum *datums)
 
static Listmerge_publications (List *oldpublist, List *newpublist, bool addpub, const char *subname)
 
static void ReportSlotConnectionError (List *rstates, Oid subid, char *slotname, char *err)
 
static void parse_subscription_options (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)
 
static Datum publicationListToArray (List *publist)
 
ObjectAddress CreateSubscription (CreateSubscriptionStmt *stmt, bool isTopLevel)
 
static void AlterSubscription_refresh (Subscription *sub, bool copy_data)
 
ObjectAddress AlterSubscription (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)
 

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:483
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:3645
#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:786
#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

◆ AlterSubscription_refresh()

static void AlterSubscription_refresh ( Subscription sub,
bool  copy_data 
)
static

Definition at line 542 of file subscriptioncmds.c.

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

Referenced by AlterSubscription().

543 {
544  char *err;
545  List *pubrel_names;
546  List *subrel_states;
547  Oid *subrel_local_oids;
548  Oid *pubrel_local_oids;
549  ListCell *lc;
550  int off;
551  int remove_rel_len;
552  Relation rel = NULL;
553  typedef struct SubRemoveRels
554  {
555  Oid relid;
556  char state;
557  } SubRemoveRels;
558  SubRemoveRels *sub_remove_rels;
559 
560  /* Load the library providing us libpq calls. */
561  load_file("libpqwalreceiver", false);
562 
563  PG_TRY();
564  {
565  /* Try to connect to the publisher. */
566  wrconn = walrcv_connect(sub->conninfo, true, sub->name, &err);
567  if (!wrconn)
568  ereport(ERROR,
569  (errmsg("could not connect to the publisher: %s", err)));
570 
571  /* Get the table list from publisher. */
572  pubrel_names = fetch_table_list(wrconn, sub->publications);
573 
574  /* Get local table list. */
575  subrel_states = GetSubscriptionRelations(sub->oid);
576 
577  /*
578  * Build qsorted array of local table oids for faster lookup. This can
579  * potentially contain all tables in the database so speed of lookup
580  * is important.
581  */
582  subrel_local_oids = palloc(list_length(subrel_states) * sizeof(Oid));
583  off = 0;
584  foreach(lc, subrel_states)
585  {
587 
588  subrel_local_oids[off++] = relstate->relid;
589  }
590  qsort(subrel_local_oids, list_length(subrel_states),
591  sizeof(Oid), oid_cmp);
592 
593  /*
594  * Rels that we want to remove from subscription and drop any slots
595  * and origins corresponding to them.
596  */
597  sub_remove_rels = palloc(list_length(subrel_states) * sizeof(SubRemoveRels));
598 
599  /*
600  * Walk over the remote tables and try to match them to locally known
601  * tables. If the table is not known locally create a new state for
602  * it.
603  *
604  * Also builds array of local oids of remote tables for the next step.
605  */
606  off = 0;
607  pubrel_local_oids = palloc(list_length(pubrel_names) * sizeof(Oid));
608 
609  foreach(lc, pubrel_names)
610  {
611  RangeVar *rv = (RangeVar *) lfirst(lc);
612  Oid relid;
613 
614  relid = RangeVarGetRelid(rv, AccessShareLock, false);
615 
616  /* Check for supported relkind. */
618  rv->schemaname, rv->relname);
619 
620  pubrel_local_oids[off++] = relid;
621 
622  if (!bsearch(&relid, subrel_local_oids,
623  list_length(subrel_states), sizeof(Oid), oid_cmp))
624  {
625  AddSubscriptionRelState(sub->oid, relid,
626  copy_data ? SUBREL_STATE_INIT : SUBREL_STATE_READY,
628  ereport(DEBUG1,
629  (errmsg_internal("table \"%s.%s\" added to subscription \"%s\"",
630  rv->schemaname, rv->relname, sub->name)));
631  }
632  }
633 
634  /*
635  * Next remove state for tables we should not care about anymore using
636  * the data we collected above
637  */
638  qsort(pubrel_local_oids, list_length(pubrel_names),
639  sizeof(Oid), oid_cmp);
640 
641  remove_rel_len = 0;
642  for (off = 0; off < list_length(subrel_states); off++)
643  {
644  Oid relid = subrel_local_oids[off];
645 
646  if (!bsearch(&relid, pubrel_local_oids,
647  list_length(pubrel_names), sizeof(Oid), oid_cmp))
648  {
649  char state;
650  XLogRecPtr statelsn;
651 
652  /*
653  * Lock pg_subscription_rel with AccessExclusiveLock to
654  * prevent any race conditions with the apply worker
655  * re-launching workers at the same time this code is trying
656  * to remove those tables.
657  *
658  * Even if new worker for this particular rel is restarted it
659  * won't be able to make any progress as we hold exclusive
660  * lock on subscription_rel till the transaction end. It will
661  * simply exit as there is no corresponding rel entry.
662  *
663  * This locking also ensures that the state of rels won't
664  * change till we are done with this refresh operation.
665  */
666  if (!rel)
667  rel = table_open(SubscriptionRelRelationId, AccessExclusiveLock);
668 
669  /* Last known rel state. */
670  state = GetSubscriptionRelState(sub->oid, relid, &statelsn);
671 
672  sub_remove_rels[remove_rel_len].relid = relid;
673  sub_remove_rels[remove_rel_len++].state = state;
674 
675  RemoveSubscriptionRel(sub->oid, relid);
676 
677  logicalrep_worker_stop(sub->oid, relid);
678 
679  /*
680  * For READY state, we would have already dropped the
681  * tablesync origin.
682  */
683  if (state != SUBREL_STATE_READY)
684  {
685  char originname[NAMEDATALEN];
686 
687  /*
688  * Drop the tablesync's origin tracking if exists.
689  *
690  * It is possible that the origin is not yet created for
691  * tablesync worker, this can happen for the states before
692  * SUBREL_STATE_FINISHEDCOPY. The apply worker can also
693  * concurrently try to drop the origin and by this time
694  * the origin might be already removed. For these reasons,
695  * passing missing_ok = true.
696  */
697  ReplicationOriginNameForTablesync(sub->oid, relid, originname,
698  sizeof(originname));
699  replorigin_drop_by_name(originname, true, false);
700  }
701 
702  ereport(DEBUG1,
703  (errmsg_internal("table \"%s.%s\" removed from subscription \"%s\"",
705  get_rel_name(relid),
706  sub->name)));
707  }
708  }
709 
710  /*
711  * Drop the tablesync slots associated with removed tables. This has
712  * to be at the end because otherwise if there is an error while doing
713  * the database operations we won't be able to rollback dropped slots.
714  */
715  for (off = 0; off < remove_rel_len; off++)
716  {
717  if (sub_remove_rels[off].state != SUBREL_STATE_READY &&
718  sub_remove_rels[off].state != SUBREL_STATE_SYNCDONE)
719  {
720  char syncslotname[NAMEDATALEN] = {0};
721 
722  /*
723  * For READY/SYNCDONE states we know the tablesync slot has
724  * already been dropped by the tablesync worker.
725  *
726  * For other states, there is no certainty, maybe the slot
727  * does not exist yet. Also, if we fail after removing some of
728  * the slots, next time, it will again try to drop already
729  * dropped slots and fail. For these reasons, we allow
730  * missing_ok = true for the drop.
731  */
732  ReplicationSlotNameForTablesync(sub->oid, sub_remove_rels[off].relid,
733  syncslotname, sizeof(syncslotname));
734  ReplicationSlotDropAtPubNode(wrconn, syncslotname, true);
735  }
736  }
737  }
738  PG_FINALLY();
739  {
740  if (wrconn)
742  }
743  PG_END_TRY();
744 
745  if (rel)
746  table_close(rel, NoLock);
747 }
static List * fetch_table_list(WalReceiverConn *wrconn, List *publications)
WalReceiverConn * wrconn
Definition: worker.c:159
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
#define DEBUG1
Definition: elog.h:25
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
void RemoveSubscriptionRel(Oid subid, Oid relid)
void ReplicationSlotDropAtPubNode(WalReceiverConn *wrconn, char *slotname, bool missing_ok)
#define RangeVarGetRelid(relation, lockmode, missing_ok)
Definition: namespace.h:78
void replorigin_drop_by_name(char *name, bool missing_ok, bool nowait)
Definition: origin.c:414
char get_rel_relkind(Oid relid)
Definition: lsyscache.c:1974
Oid get_rel_namespace(Oid relid)
Definition: lsyscache.c:1923
#define AccessShareLock
Definition: lockdefs.h:36
unsigned int Oid
Definition: postgres_ext.h:31
char * schemaname
Definition: primnodes.h:67
#define NAMEDATALEN
char * relname
Definition: primnodes.h:68
#define ERROR
Definition: elog.h:46
void AddSubscriptionRelState(Oid subid, Oid relid, char state, XLogRecPtr sublsn)
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3316
#define NoLock
Definition: lockdefs.h:34
void logicalrep_worker_stop(Oid subid, Oid relid)
Definition: launcher.c:442
List * GetSubscriptionRelations(Oid subid)
List * publications
void CheckSubscriptionRelkind(char relkind, const char *nspname, const char *relname)
#define PG_FINALLY()
Definition: elog.h:330
char GetSubscriptionRelState(Oid subid, Oid relid, XLogRecPtr *sublsn)
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define lfirst(lc)
Definition: pg_list.h:169
Definition: regguts.h:317
void load_file(const char *filename, bool restricted)
Definition: dfmgr.c:146
int oid_cmp(const void *p1, const void *p2)
Definition: oid.c:336
static int list_length(const List *l)
Definition: pg_list.h:149
void ReplicationOriginNameForTablesync(Oid suboid, Oid relid, char *originname, int szorgname)
Definition: tablesync.c:898
#define walrcv_disconnect(conn)
Definition: walreceiver.h:429
#define AccessExclusiveLock
Definition: lockdefs.h:45
void * palloc(Size size)
Definition: mcxt.c:1062
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define qsort(a, b, c, d)
Definition: port.h:504
#define PG_TRY()
Definition: elog.h:313
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Definition: pg_list.h:50
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1899
#define PG_END_TRY()
Definition: elog.h:338
void ReplicationSlotNameForTablesync(Oid suboid, Oid relid, char *syncslotname, int szslot)
Definition: tablesync.c:885
#define walrcv_connect(conninfo, logical, appname, err)
Definition: walreceiver.h:401

◆ 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_internal()

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

Definition at line 1374 of file subscriptioncmds.c.

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

Referenced by AlterSubscriptionOwner(), and AlterSubscriptionOwner_oid().

1375 {
1376  Form_pg_subscription form;
1377 
1378  form = (Form_pg_subscription) GETSTRUCT(tup);
1379 
1380  if (form->subowner == newOwnerId)
1381  return;
1382 
1383  if (!pg_subscription_ownercheck(form->oid, GetUserId()))
1385  NameStr(form->subname));
1386 
1387  /* New owner must be a superuser */
1388  if (!superuser_arg(newOwnerId))
1389  ereport(ERROR,
1390  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1391  errmsg("permission denied to change owner of subscription \"%s\"",
1392  NameStr(form->subname)),
1393  errhint("The owner of a subscription must be a superuser.")));
1394 
1395  form->subowner = newOwnerId;
1396  CatalogTupleUpdate(rel, &tup->t_self, tup);
1397 
1398  /* Update owner dependency reference */
1399  changeDependencyOnOwner(SubscriptionRelationId,
1400  form->oid,
1401  newOwnerId);
1402 
1403  InvokeObjectPostAlterHook(SubscriptionRelationId,
1404  form->oid, 0);
1405 }
int errhint(const char *fmt,...)
Definition: elog.c:1156
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
Oid GetUserId(void)
Definition: miscinit.c:478
int errcode(int sqlerrcode)
Definition: elog.c:698
FormData_pg_subscription * Form_pg_subscription
void changeDependencyOnOwner(Oid classId, Oid objectId, Oid newOwnerId)
Definition: pg_shdepend.c:313
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 InvokeObjectPostAlterHook(classId, objectId, subId)
Definition: objectaccess.h:175
bool superuser_arg(Oid roleid)
Definition: superuser.c:56
#define ereport(elevel,...)
Definition: elog.h:157
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:301
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define NameStr(name)
Definition: c.h:681
bool pg_subscription_ownercheck(Oid sub_oid, Oid roleid)
Definition: aclchk.c:5387

◆ 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

◆ check_duplicates_in_publist()

static void check_duplicates_in_publist ( List publist,
Datum datums 
)
static

Definition at line 1585 of file subscriptioncmds.c.

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

Referenced by merge_publications(), and publicationListToArray().

1586 {
1587  ListCell *cell;
1588  int j = 0;
1589 
1590  foreach(cell, publist)
1591  {
1592  char *name = strVal(lfirst(cell));
1593  ListCell *pcell;
1594 
1595  foreach(pcell, publist)
1596  {
1597  char *pname = strVal(lfirst(pcell));
1598 
1599  if (pcell == cell)
1600  break;
1601 
1602  if (strcmp(name, pname) == 0)
1603  ereport(ERROR,
1604  (errcode(ERRCODE_SYNTAX_ERROR),
1605  errmsg("publication name \"%s\" used more than once",
1606  pname)));
1607  }
1608 
1609  if (datums)
1610  datums[j++] = CStringGetTextDatum(name);
1611  }
1612 }
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:698
#define ERROR
Definition: elog.h:46
#define ereport(elevel,...)
Definition: elog.h:157
#define lfirst(lc)
Definition: pg_list.h:169
const char * name
Definition: encode.c:515
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define CStringGetTextDatum(s)
Definition: builtins.h:82

◆ 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
WalReceiverConn * wrconn
Definition: worker.c:159
#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:483
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
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:786
#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;
1065  WalReceiverConn *wrconn = 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
WalReceiverConn * wrconn
Definition: worker.c:159
List * logicalrep_workers_find(Oid subid, bool only_running)
Definition: launcher.c:249
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
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1805
#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:442
#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:898
#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:885
bool pg_subscription_ownercheck(Oid sub_oid, Oid roleid)
Definition: aclchk.c:5387
#define walrcv_connect(conninfo, logical, appname, err)
Definition: walreceiver.h:401

◆ fetch_table_list()

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

Definition at line 1473 of file subscriptioncmds.c.

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

Referenced by AlterSubscription_refresh(), and CreateSubscription().

1474 {
1475  WalRcvExecResult *res;
1476  StringInfoData cmd;
1477  TupleTableSlot *slot;
1478  Oid tableRow[2] = {TEXTOID, TEXTOID};
1479  ListCell *lc;
1480  bool first;
1481  List *tablelist = NIL;
1482 
1483  Assert(list_length(publications) > 0);
1484 
1485  initStringInfo(&cmd);
1486  appendStringInfoString(&cmd, "SELECT DISTINCT t.schemaname, t.tablename\n"
1487  " FROM pg_catalog.pg_publication_tables t\n"
1488  " WHERE t.pubname IN (");
1489  first = true;
1490  foreach(lc, publications)
1491  {
1492  char *pubname = strVal(lfirst(lc));
1493 
1494  if (first)
1495  first = false;
1496  else
1497  appendStringInfoString(&cmd, ", ");
1498 
1500  }
1501  appendStringInfoChar(&cmd, ')');
1502 
1503  res = walrcv_exec(wrconn, cmd.data, 2, tableRow);
1504  pfree(cmd.data);
1505 
1506  if (res->status != WALRCV_OK_TUPLES)
1507  ereport(ERROR,
1508  (errmsg("could not receive list of replicated tables from the publisher: %s",
1509  res->err)));
1510 
1511  /* Process tables. */
1513  while (tuplestore_gettupleslot(res->tuplestore, true, false, slot))
1514  {
1515  char *nspname;
1516  char *relname;
1517  bool isnull;
1518  RangeVar *rv;
1519 
1520  nspname = TextDatumGetCString(slot_getattr(slot, 1, &isnull));
1521  Assert(!isnull);
1522  relname = TextDatumGetCString(slot_getattr(slot, 2, &isnull));
1523  Assert(!isnull);
1524 
1525  rv = makeRangeVar(nspname, relname, -1);
1526  tablelist = lappend(tablelist, rv);
1527 
1528  ExecClearTuple(slot);
1529  }
1531 
1532  walrcv_clear_result(res);
1533 
1534  return tablelist;
1535 }
#define NIL
Definition: pg_list.h:65
char * quote_literal_cstr(const char *rawstr)
Definition: quote.c:102
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:425
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1208
#define strVal(v)
Definition: value.h:54
NameData relname
Definition: pg_class.h:38
unsigned int Oid
Definition: postgres_ext.h:31
static void walrcv_clear_result(WalRcvExecResult *walres)
Definition: walreceiver.h:433
void pfree(void *pointer)
Definition: mcxt.c:1169
TupleDesc tupledesc
Definition: walreceiver.h:218
#define ERROR
Definition: elog.h:46
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1224
List * lappend(List *list, void *datum)
Definition: list.c:336
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
#define TextDatumGetCString(d)
Definition: builtins.h:83
static Datum slot_getattr(TupleTableSlot *slot, int attnum, bool *isnull)
Definition: tuptable.h:381
#define ereport(elevel,...)
Definition: elog.h:157
bool tuplestore_gettupleslot(Tuplestorestate *state, bool forward, bool copy, TupleTableSlot *slot)
Definition: tuplestore.c:1078
Tuplestorestate * tuplestore
Definition: walreceiver.h:217
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
WalRcvExecStatus status
Definition: walreceiver.h:214
static int list_length(const List *l)
Definition: pg_list.h:149
int errmsg(const char *fmt,...)
Definition: elog.c:909
Definition: pg_list.h:50
const TupleTableSlotOps TTSOpsMinimalTuple
Definition: execTuples.c:85
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition: makefuncs.c:422
#define walrcv_exec(conn, exec, nRetTypes, retTypes)
Definition: walreceiver.h:427

◆ merge_publications()

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

Definition at line 1625 of file subscriptioncmds.c.

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

Referenced by AlterSubscription().

1626 {
1627  ListCell *lc;
1628 
1629  oldpublist = list_copy(oldpublist);
1630 
1631  check_duplicates_in_publist(newpublist, NULL);
1632 
1633  foreach(lc, newpublist)
1634  {
1635  char *name = strVal(lfirst(lc));
1636  ListCell *lc2;
1637  bool found = false;
1638 
1639  foreach(lc2, oldpublist)
1640  {
1641  char *pubname = strVal(lfirst(lc2));
1642 
1643  if (strcmp(name, pubname) == 0)
1644  {
1645  found = true;
1646  if (addpub)
1647  ereport(ERROR,
1649  errmsg("publication \"%s\" is already in subscription \"%s\"",
1650  name, subname)));
1651  else
1652  oldpublist = foreach_delete_current(oldpublist, lc2);
1653 
1654  break;
1655  }
1656  }
1657 
1658  if (addpub && !found)
1659  oldpublist = lappend(oldpublist, makeString(name));
1660  else if (!addpub && !found)
1661  ereport(ERROR,
1662  (errcode(ERRCODE_SYNTAX_ERROR),
1663  errmsg("publication \"%s\" is not in subscription \"%s\"",
1664  name, subname)));
1665  }
1666 
1667  /*
1668  * XXX Probably no strong reason for this, but for now it's to make ALTER
1669  * SUBSCRIPTION ... DROP PUBLICATION consistent with SET PUBLICATION.
1670  */
1671  if (!oldpublist)
1672  ereport(ERROR,
1673  (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
1674  errmsg("subscription must contain at least one publication")));
1675 
1676  return oldpublist;
1677 }
Value * makeString(char *str)
Definition: value.c:53
List * list_copy(const List *oldlist)
Definition: list.c:1418
#define strVal(v)
Definition: value.h:54
int errcode(int sqlerrcode)
Definition: elog.c:698
NameData subname
#define foreach_delete_current(lst, cell)
Definition: pg_list.h:369
#define ERROR
Definition: elog.h:46
List * lappend(List *list, void *datum)
Definition: list.c:336
static void check_duplicates_in_publist(List *publist, Datum *datums)
#define ereport(elevel,...)
Definition: elog.h:157
#define lfirst(lc)
Definition: pg_list.h:169
const char * name
Definition: encode.c:515
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:32

◆ parse_subscription_options()

static void parse_subscription_options ( 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 
)
static

Definition at line 63 of file subscriptioncmds.c.

References Assert, connect, defGetBoolean(), defGetString(), DefElem::defname, ereport, errcode(), errmsg(), ERROR, GUC_ACTION_SET, lfirst, PGC_BACKEND, PGC_S_TEST, and set_config_option().

Referenced by AlterSubscription(), and CreateSubscription().

73 {
74  ListCell *lc;
75  bool connect_given = false;
76  bool create_slot_given = false;
77  bool copy_data_given = false;
78  bool refresh_given = false;
79 
80  /* If connect is specified, the others also need to be. */
81  Assert(!connect || (enabled && create_slot && copy_data));
82 
83  if (connect)
84  *connect = true;
85  if (enabled)
86  {
87  *enabled_given = false;
88  *enabled = true;
89  }
90  if (create_slot)
91  *create_slot = true;
92  if (slot_name)
93  {
94  *slot_name_given = false;
95  *slot_name = NULL;
96  }
97  if (copy_data)
98  *copy_data = true;
100  *synchronous_commit = NULL;
101  if (refresh)
102  *refresh = true;
103  if (binary)
104  {
105  *binary_given = false;
106  *binary = false;
107  }
108  if (streaming)
109  {
110  *streaming_given = false;
111  *streaming = false;
112  }
113 
114  /* Parse options */
115  foreach(lc, options)
116  {
117  DefElem *defel = (DefElem *) lfirst(lc);
118 
119  if (strcmp(defel->defname, "connect") == 0 && connect)
120  {
121  if (connect_given)
122  ereport(ERROR,
123  (errcode(ERRCODE_SYNTAX_ERROR),
124  errmsg("conflicting or redundant options")));
125 
126  connect_given = true;
127  *connect = defGetBoolean(defel);
128  }
129  else if (strcmp(defel->defname, "enabled") == 0 && enabled)
130  {
131  if (*enabled_given)
132  ereport(ERROR,
133  (errcode(ERRCODE_SYNTAX_ERROR),
134  errmsg("conflicting or redundant options")));
135 
136  *enabled_given = true;
137  *enabled = defGetBoolean(defel);
138  }
139  else if (strcmp(defel->defname, "create_slot") == 0 && create_slot)
140  {
141  if (create_slot_given)
142  ereport(ERROR,
143  (errcode(ERRCODE_SYNTAX_ERROR),
144  errmsg("conflicting or redundant options")));
145 
146  create_slot_given = true;
147  *create_slot = defGetBoolean(defel);
148  }
149  else if (strcmp(defel->defname, "slot_name") == 0 && slot_name)
150  {
151  if (*slot_name_given)
152  ereport(ERROR,
153  (errcode(ERRCODE_SYNTAX_ERROR),
154  errmsg("conflicting or redundant options")));
155 
156  *slot_name_given = true;
157  *slot_name = defGetString(defel);
158 
159  /* Setting slot_name = NONE is treated as no slot name. */
160  if (strcmp(*slot_name, "none") == 0)
161  *slot_name = NULL;
162  }
163  else if (strcmp(defel->defname, "copy_data") == 0 && copy_data)
164  {
165  if (copy_data_given)
166  ereport(ERROR,
167  (errcode(ERRCODE_SYNTAX_ERROR),
168  errmsg("conflicting or redundant options")));
169 
170  copy_data_given = true;
171  *copy_data = defGetBoolean(defel);
172  }
173  else if (strcmp(defel->defname, "synchronous_commit") == 0 &&
175  {
176  if (*synchronous_commit)
177  ereport(ERROR,
178  (errcode(ERRCODE_SYNTAX_ERROR),
179  errmsg("conflicting or redundant options")));
180 
182 
183  /* Test if the given value is valid for synchronous_commit GUC. */
184  (void) set_config_option("synchronous_commit", *synchronous_commit,
186  false, 0, false);
187  }
188  else if (strcmp(defel->defname, "refresh") == 0 && refresh)
189  {
190  if (refresh_given)
191  ereport(ERROR,
192  (errcode(ERRCODE_SYNTAX_ERROR),
193  errmsg("conflicting or redundant options")));
194 
195  refresh_given = true;
196  *refresh = defGetBoolean(defel);
197  }
198  else if (strcmp(defel->defname, "binary") == 0 && binary)
199  {
200  if (*binary_given)
201  ereport(ERROR,
202  (errcode(ERRCODE_SYNTAX_ERROR),
203  errmsg("conflicting or redundant options")));
204 
205  *binary_given = true;
206  *binary = defGetBoolean(defel);
207  }
208  else if (strcmp(defel->defname, "streaming") == 0 && streaming)
209  {
210  if (*streaming_given)
211  ereport(ERROR,
212  (errcode(ERRCODE_SYNTAX_ERROR),
213  errmsg("conflicting or redundant options")));
214 
215  *streaming_given = true;
216  *streaming = defGetBoolean(defel);
217  }
218  else
219  ereport(ERROR,
220  (errcode(ERRCODE_SYNTAX_ERROR),
221  errmsg("unrecognized subscription parameter: \"%s\"", defel->defname)));
222  }
223 
224  /*
225  * We've been explicitly asked to not connect, that requires some
226  * additional processing.
227  */
228  if (connect && !*connect)
229  {
230  /* Check for incompatible options from the user. */
231  if (enabled && *enabled_given && *enabled)
232  ereport(ERROR,
233  (errcode(ERRCODE_SYNTAX_ERROR),
234  /*- translator: both %s are strings of the form "option = value" */
235  errmsg("%s and %s are mutually exclusive options",
236  "connect = false", "enabled = true")));
237 
238  if (create_slot && create_slot_given && *create_slot)
239  ereport(ERROR,
240  (errcode(ERRCODE_SYNTAX_ERROR),
241  errmsg("%s and %s are mutually exclusive options",
242  "connect = false", "create_slot = true")));
243 
244  if (copy_data && copy_data_given && *copy_data)
245  ereport(ERROR,
246  (errcode(ERRCODE_SYNTAX_ERROR),
247  errmsg("%s and %s are mutually exclusive options",
248  "connect = false", "copy_data = true")));
249 
250  /* Change the defaults of other options. */
251  *enabled = false;
252  *create_slot = false;
253  *copy_data = false;
254  }
255 
256  /*
257  * Do additional checking for disallowed combination when slot_name = NONE
258  * was used.
259  */
260  if (slot_name && *slot_name_given && !*slot_name)
261  {
262  if (enabled && *enabled_given && *enabled)
263  ereport(ERROR,
264  (errcode(ERRCODE_SYNTAX_ERROR),
265  /*- translator: both %s are strings of the form "option = value" */
266  errmsg("%s and %s are mutually exclusive options",
267  "slot_name = NONE", "enabled = true")));
268 
269  if (create_slot && create_slot_given && *create_slot)
270  ereport(ERROR,
271  (errcode(ERRCODE_SYNTAX_ERROR),
272  errmsg("%s and %s are mutually exclusive options",
273  "slot_name = NONE", "create_slot = true")));
274 
275  if (enabled && !*enabled_given && *enabled)
276  ereport(ERROR,
277  (errcode(ERRCODE_SYNTAX_ERROR),
278  /*- translator: both %s are strings of the form "option = value" */
279  errmsg("subscription with %s must also set %s",
280  "slot_name = NONE", "enabled = false")));
281 
282  if (create_slot && !create_slot_given && *create_slot)
283  ereport(ERROR,
284  (errcode(ERRCODE_SYNTAX_ERROR),
285  errmsg("subscription with %s must also set %s",
286  "slot_name = NONE", "create_slot = false")));
287  }
288 }
static bool create_slot
int errcode(int sqlerrcode)
Definition: elog.c:698
#define connect(s, name, namelen)
Definition: win32_port.h:463
bool defGetBoolean(DefElem *def)
Definition: define.c:111
#define ERROR
Definition: elog.h:46
char * defGetString(DefElem *def)
Definition: define.c:49
int synchronous_commit
Definition: xact.c:83
#define ereport(elevel,...)
Definition: elog.h:157
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
int errmsg(const char *fmt,...)
Definition: elog.c:909
char * defname
Definition: parsenodes.h:746
int set_config_option(const char *name, const char *value, GucContext context, GucSource source, GucAction action, bool changeVal, int elevel, bool is_reload)
Definition: guc.c:7312

◆ publicationListToArray()

static Datum publicationListToArray ( List publist)
static

Definition at line 294 of file subscriptioncmds.c.

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

Referenced by AlterSubscription(), and CreateSubscription().

295 {
296  ArrayType *arr;
297  Datum *datums;
298  MemoryContext memcxt;
299  MemoryContext oldcxt;
300 
301  /* Create memory context for temporary allocations. */
303  "publicationListToArray to array",
305  oldcxt = MemoryContextSwitchTo(memcxt);
306 
307  datums = (Datum *) palloc(sizeof(Datum) * list_length(publist));
308 
309  check_duplicates_in_publist(publist, datums);
310 
311  MemoryContextSwitchTo(oldcxt);
312 
313  arr = construct_array(datums, list_length(publist),
314  TEXTOID, -1, false, TYPALIGN_INT);
315 
316  MemoryContextDelete(memcxt);
317 
318  return PointerGetDatum(arr);
319 }
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:218
#define AllocSetContextCreate
Definition: memutils.h:173
#define PointerGetDatum(X)
Definition: postgres.h:600
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
ArrayType * construct_array(Datum *elems, int nelems, Oid elmtype, int elmlen, bool elmbyval, char elmalign)
Definition: arrayfuncs.c:3318
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:195
MemoryContext CurrentMemoryContext
Definition: mcxt.c:42
static void check_duplicates_in_publist(List *publist, Datum *datums)
uintptr_t Datum
Definition: postgres.h:411
static int list_length(const List *l)
Definition: pg_list.h:149
void * palloc(Size size)
Definition: mcxt.c:1062

◆ ReplicationSlotDropAtPubNode()

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

Definition at line 1320 of file subscriptioncmds.c.

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

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

1321 {
1322  StringInfoData cmd;
1323 
1324  Assert(wrconn);
1325 
1326  load_file("libpqwalreceiver", false);
1327 
1328  initStringInfo(&cmd);
1329  appendStringInfo(&cmd, "DROP_REPLICATION_SLOT %s WAIT", quote_identifier(slotname));
1330 
1331  PG_TRY();
1332  {
1333  WalRcvExecResult *res;
1334 
1335  res = walrcv_exec(wrconn, cmd.data, 0, NULL);
1336 
1337  if (res->status == WALRCV_OK_COMMAND)
1338  {
1339  /* NOTICE. Success. */
1340  ereport(NOTICE,
1341  (errmsg("dropped replication slot \"%s\" on publisher",
1342  slotname)));
1343  }
1344  else if (res->status == WALRCV_ERROR &&
1345  missing_ok &&
1346  res->sqlstate == ERRCODE_UNDEFINED_OBJECT)
1347  {
1348  /* LOG. Error, but missing_ok = true. */
1349  ereport(LOG,
1350  (errmsg("could not drop replication slot \"%s\" on publisher: %s",
1351  slotname, res->err)));
1352  }
1353  else
1354  {
1355  /* ERROR. */
1356  ereport(ERROR,
1357  (errmsg("could not drop replication slot \"%s\" on publisher: %s",
1358  slotname, res->err)));
1359  }
1360 
1361  walrcv_clear_result(res);
1362  }
1363  PG_FINALLY();
1364  {
1365  pfree(cmd.data);
1366  }
1367  PG_END_TRY();
1368 }
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:11323
#define LOG
Definition: elog.h:26
static void walrcv_clear_result(WalRcvExecResult *walres)
Definition: walreceiver.h:433
void pfree(void *pointer)
Definition: mcxt.c:1169
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
#define ERROR
Definition: elog.h:46
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
#define PG_FINALLY()
Definition: elog.h:330
#define ereport(elevel,...)
Definition: elog.h:157
#define NOTICE
Definition: elog.h:37
#define Assert(condition)
Definition: c.h:804
WalRcvExecStatus status
Definition: walreceiver.h:214
void load_file(const char *filename, bool restricted)
Definition: dfmgr.c:146
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define PG_TRY()
Definition: elog.h:313
#define PG_END_TRY()
Definition: elog.h:338
#define walrcv_exec(conn, exec, nRetTypes, retTypes)
Definition: walreceiver.h:427

◆ ReportSlotConnectionError()

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

Definition at line 1543 of file subscriptioncmds.c.

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

Referenced by DropSubscription().

1544 {
1545  ListCell *lc;
1546 
1547  foreach(lc, rstates)
1548  {
1550  Oid relid = rstate->relid;
1551 
1552  /* Only cleanup resources of tablesync workers */
1553  if (!OidIsValid(relid))
1554  continue;
1555 
1556  /*
1557  * Caller needs to ensure that relstate doesn't change underneath us.
1558  * See DropSubscription where we get the relstates.
1559  */
1560  if (rstate->state != SUBREL_STATE_SYNCDONE)
1561  {
1562  char syncslotname[NAMEDATALEN] = {0};
1563 
1564  ReplicationSlotNameForTablesync(subid, relid, syncslotname,
1565  sizeof(syncslotname));
1566  elog(WARNING, "could not drop tablesync replication slot \"%s\"",
1567  syncslotname);
1568  }
1569  }
1570 
1571  ereport(ERROR,
1572  (errmsg("could not connect to publisher when attempting to "
1573  "drop replication slot \"%s\": %s", slotname, err),
1574  /* translator: %s is an SQL ALTER command */
1575  errhint("Use %s to disassociate the subscription from the slot.",
1576  "ALTER SUBSCRIPTION ... SET (slot_name = NONE)")));
1577 }
int errhint(const char *fmt,...)
Definition: elog.c:1156
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:710
#define NAMEDATALEN
#define ERROR
Definition: elog.h:46
#define WARNING
Definition: elog.h:40
#define ereport(elevel,...)
Definition: elog.h:157
#define lfirst(lc)
Definition: pg_list.h:169
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define elog(elevel,...)
Definition: elog.h:232
void ReplicationSlotNameForTablesync(Oid suboid, Oid relid, char *syncslotname, int szslot)
Definition: tablesync.c:885