LCOV - code coverage report
Current view: top level - src/backend/commands - subscriptioncmds.c (source / functions) Hit Total Coverage
Test: PostgreSQL 17devel Lines: 719 817 88.0 %
Date: 2024-04-25 11:11:38 Functions: 16 18 88.9 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * subscriptioncmds.c
       4             :  *      subscription catalog manipulation functions
       5             :  *
       6             :  * Portions Copyright (c) 1996-2024, PostgreSQL Global Development Group
       7             :  * Portions Copyright (c) 1994, Regents of the University of California
       8             :  *
       9             :  * IDENTIFICATION
      10             :  *      src/backend/commands/subscriptioncmds.c
      11             :  *
      12             :  *-------------------------------------------------------------------------
      13             :  */
      14             : 
      15             : #include "postgres.h"
      16             : 
      17             : #include "access/htup_details.h"
      18             : #include "access/table.h"
      19             : #include "access/xact.h"
      20             : #include "catalog/catalog.h"
      21             : #include "catalog/dependency.h"
      22             : #include "catalog/indexing.h"
      23             : #include "catalog/namespace.h"
      24             : #include "catalog/objectaccess.h"
      25             : #include "catalog/objectaddress.h"
      26             : #include "catalog/pg_authid_d.h"
      27             : #include "catalog/pg_database_d.h"
      28             : #include "catalog/pg_subscription.h"
      29             : #include "catalog/pg_subscription_rel.h"
      30             : #include "catalog/pg_type.h"
      31             : #include "commands/dbcommands.h"
      32             : #include "commands/defrem.h"
      33             : #include "commands/event_trigger.h"
      34             : #include "commands/subscriptioncmds.h"
      35             : #include "executor/executor.h"
      36             : #include "miscadmin.h"
      37             : #include "nodes/makefuncs.h"
      38             : #include "pgstat.h"
      39             : #include "replication/logicallauncher.h"
      40             : #include "replication/logicalworker.h"
      41             : #include "replication/origin.h"
      42             : #include "replication/slot.h"
      43             : #include "replication/walreceiver.h"
      44             : #include "replication/walsender.h"
      45             : #include "replication/worker_internal.h"
      46             : #include "storage/lmgr.h"
      47             : #include "utils/acl.h"
      48             : #include "utils/builtins.h"
      49             : #include "utils/guc.h"
      50             : #include "utils/lsyscache.h"
      51             : #include "utils/memutils.h"
      52             : #include "utils/pg_lsn.h"
      53             : #include "utils/syscache.h"
      54             : 
      55             : /*
      56             :  * Options that can be specified by the user in CREATE/ALTER SUBSCRIPTION
      57             :  * command.
      58             :  */
      59             : #define SUBOPT_CONNECT              0x00000001
      60             : #define SUBOPT_ENABLED              0x00000002
      61             : #define SUBOPT_CREATE_SLOT          0x00000004
      62             : #define SUBOPT_SLOT_NAME            0x00000008
      63             : #define SUBOPT_COPY_DATA            0x00000010
      64             : #define SUBOPT_SYNCHRONOUS_COMMIT   0x00000020
      65             : #define SUBOPT_REFRESH              0x00000040
      66             : #define SUBOPT_BINARY               0x00000080
      67             : #define SUBOPT_STREAMING            0x00000100
      68             : #define SUBOPT_TWOPHASE_COMMIT      0x00000200
      69             : #define SUBOPT_DISABLE_ON_ERR       0x00000400
      70             : #define SUBOPT_PASSWORD_REQUIRED    0x00000800
      71             : #define SUBOPT_RUN_AS_OWNER         0x00001000
      72             : #define SUBOPT_FAILOVER             0x00002000
      73             : #define SUBOPT_LSN                  0x00004000
      74             : #define SUBOPT_ORIGIN               0x00008000
      75             : 
      76             : /* check if the 'val' has 'bits' set */
      77             : #define IsSet(val, bits)  (((val) & (bits)) == (bits))
      78             : 
      79             : /*
      80             :  * Structure to hold a bitmap representing the user-provided CREATE/ALTER
      81             :  * SUBSCRIPTION command options and the parsed/default values of each of them.
      82             :  */
      83             : typedef struct SubOpts
      84             : {
      85             :     bits32      specified_opts;
      86             :     char       *slot_name;
      87             :     char       *synchronous_commit;
      88             :     bool        connect;
      89             :     bool        enabled;
      90             :     bool        create_slot;
      91             :     bool        copy_data;
      92             :     bool        refresh;
      93             :     bool        binary;
      94             :     char        streaming;
      95             :     bool        twophase;
      96             :     bool        disableonerr;
      97             :     bool        passwordrequired;
      98             :     bool        runasowner;
      99             :     bool        failover;
     100             :     char       *origin;
     101             :     XLogRecPtr  lsn;
     102             : } SubOpts;
     103             : 
     104             : static List *fetch_table_list(WalReceiverConn *wrconn, List *publications);
     105             : static void check_publications_origin(WalReceiverConn *wrconn,
     106             :                                       List *publications, bool copydata,
     107             :                                       char *origin, Oid *subrel_local_oids,
     108             :                                       int subrel_count, char *subname);
     109             : static void check_duplicates_in_publist(List *publist, Datum *datums);
     110             : static List *merge_publications(List *oldpublist, List *newpublist, bool addpub, const char *subname);
     111             : static void ReportSlotConnectionError(List *rstates, Oid subid, char *slotname, char *err);
     112             : 
     113             : 
     114             : /*
     115             :  * Common option parsing function for CREATE and ALTER SUBSCRIPTION commands.
     116             :  *
     117             :  * Since not all options can be specified in both commands, this function
     118             :  * will report an error if mutually exclusive options are specified.
     119             :  */
     120             : static void
     121         824 : parse_subscription_options(ParseState *pstate, List *stmt_options,
     122             :                            bits32 supported_opts, SubOpts *opts)
     123             : {
     124             :     ListCell   *lc;
     125             : 
     126             :     /* Start out with cleared opts. */
     127         824 :     memset(opts, 0, sizeof(SubOpts));
     128             : 
     129             :     /* caller must expect some option */
     130             :     Assert(supported_opts != 0);
     131             : 
     132             :     /* If connect option is supported, these others also need to be. */
     133             :     Assert(!IsSet(supported_opts, SUBOPT_CONNECT) ||
     134             :            IsSet(supported_opts, SUBOPT_ENABLED | SUBOPT_CREATE_SLOT |
     135             :                  SUBOPT_COPY_DATA));
     136             : 
     137             :     /* Set default values for the supported options. */
     138         824 :     if (IsSet(supported_opts, SUBOPT_CONNECT))
     139         416 :         opts->connect = true;
     140         824 :     if (IsSet(supported_opts, SUBOPT_ENABLED))
     141         486 :         opts->enabled = true;
     142         824 :     if (IsSet(supported_opts, SUBOPT_CREATE_SLOT))
     143         416 :         opts->create_slot = true;
     144         824 :     if (IsSet(supported_opts, SUBOPT_COPY_DATA))
     145         546 :         opts->copy_data = true;
     146         824 :     if (IsSet(supported_opts, SUBOPT_REFRESH))
     147          82 :         opts->refresh = true;
     148         824 :     if (IsSet(supported_opts, SUBOPT_BINARY))
     149         600 :         opts->binary = false;
     150         824 :     if (IsSet(supported_opts, SUBOPT_STREAMING))
     151         600 :         opts->streaming = LOGICALREP_STREAM_OFF;
     152         824 :     if (IsSet(supported_opts, SUBOPT_TWOPHASE_COMMIT))
     153         416 :         opts->twophase = false;
     154         824 :     if (IsSet(supported_opts, SUBOPT_DISABLE_ON_ERR))
     155         600 :         opts->disableonerr = false;
     156         824 :     if (IsSet(supported_opts, SUBOPT_PASSWORD_REQUIRED))
     157         600 :         opts->passwordrequired = true;
     158         824 :     if (IsSet(supported_opts, SUBOPT_RUN_AS_OWNER))
     159         600 :         opts->runasowner = false;
     160         824 :     if (IsSet(supported_opts, SUBOPT_FAILOVER))
     161         600 :         opts->failover = false;
     162         824 :     if (IsSet(supported_opts, SUBOPT_ORIGIN))
     163         600 :         opts->origin = pstrdup(LOGICALREP_ORIGIN_ANY);
     164             : 
     165             :     /* Parse options */
     166        1608 :     foreach(lc, stmt_options)
     167             :     {
     168         844 :         DefElem    *defel = (DefElem *) lfirst(lc);
     169             : 
     170         844 :         if (IsSet(supported_opts, SUBOPT_CONNECT) &&
     171         492 :             strcmp(defel->defname, "connect") == 0)
     172             :         {
     173         162 :             if (IsSet(opts->specified_opts, SUBOPT_CONNECT))
     174           0 :                 errorConflictingDefElem(defel, pstate);
     175             : 
     176         162 :             opts->specified_opts |= SUBOPT_CONNECT;
     177         162 :             opts->connect = defGetBoolean(defel);
     178             :         }
     179         682 :         else if (IsSet(supported_opts, SUBOPT_ENABLED) &&
     180         400 :                  strcmp(defel->defname, "enabled") == 0)
     181             :         {
     182         106 :             if (IsSet(opts->specified_opts, SUBOPT_ENABLED))
     183           0 :                 errorConflictingDefElem(defel, pstate);
     184             : 
     185         106 :             opts->specified_opts |= SUBOPT_ENABLED;
     186         106 :             opts->enabled = defGetBoolean(defel);
     187             :         }
     188         576 :         else if (IsSet(supported_opts, SUBOPT_CREATE_SLOT) &&
     189         294 :                  strcmp(defel->defname, "create_slot") == 0)
     190             :         {
     191          40 :             if (IsSet(opts->specified_opts, SUBOPT_CREATE_SLOT))
     192           0 :                 errorConflictingDefElem(defel, pstate);
     193             : 
     194          40 :             opts->specified_opts |= SUBOPT_CREATE_SLOT;
     195          40 :             opts->create_slot = defGetBoolean(defel);
     196             :         }
     197         536 :         else if (IsSet(supported_opts, SUBOPT_SLOT_NAME) &&
     198         440 :                  strcmp(defel->defname, "slot_name") == 0)
     199             :         {
     200         142 :             if (IsSet(opts->specified_opts, SUBOPT_SLOT_NAME))
     201           0 :                 errorConflictingDefElem(defel, pstate);
     202             : 
     203         142 :             opts->specified_opts |= SUBOPT_SLOT_NAME;
     204         142 :             opts->slot_name = defGetString(defel);
     205             : 
     206             :             /* Setting slot_name = NONE is treated as no slot name. */
     207         142 :             if (strcmp(opts->slot_name, "none") == 0)
     208         108 :                 opts->slot_name = NULL;
     209             :             else
     210          34 :                 ReplicationSlotValidateName(opts->slot_name, ERROR);
     211             :         }
     212         394 :         else if (IsSet(supported_opts, SUBOPT_COPY_DATA) &&
     213         248 :                  strcmp(defel->defname, "copy_data") == 0)
     214             :         {
     215          40 :             if (IsSet(opts->specified_opts, SUBOPT_COPY_DATA))
     216           0 :                 errorConflictingDefElem(defel, pstate);
     217             : 
     218          40 :             opts->specified_opts |= SUBOPT_COPY_DATA;
     219          40 :             opts->copy_data = defGetBoolean(defel);
     220             :         }
     221         354 :         else if (IsSet(supported_opts, SUBOPT_SYNCHRONOUS_COMMIT) &&
     222         264 :                  strcmp(defel->defname, "synchronous_commit") == 0)
     223             :         {
     224          12 :             if (IsSet(opts->specified_opts, SUBOPT_SYNCHRONOUS_COMMIT))
     225           0 :                 errorConflictingDefElem(defel, pstate);
     226             : 
     227          12 :             opts->specified_opts |= SUBOPT_SYNCHRONOUS_COMMIT;
     228          12 :             opts->synchronous_commit = defGetString(defel);
     229             : 
     230             :             /* Test if the given value is valid for synchronous_commit GUC. */
     231          12 :             (void) set_config_option("synchronous_commit", opts->synchronous_commit,
     232             :                                      PGC_BACKEND, PGC_S_TEST, GUC_ACTION_SET,
     233             :                                      false, 0, false);
     234             :         }
     235         342 :         else if (IsSet(supported_opts, SUBOPT_REFRESH) &&
     236          66 :                  strcmp(defel->defname, "refresh") == 0)
     237             :         {
     238          66 :             if (IsSet(opts->specified_opts, SUBOPT_REFRESH))
     239           0 :                 errorConflictingDefElem(defel, pstate);
     240             : 
     241          66 :             opts->specified_opts |= SUBOPT_REFRESH;
     242          66 :             opts->refresh = defGetBoolean(defel);
     243             :         }
     244         276 :         else if (IsSet(supported_opts, SUBOPT_BINARY) &&
     245         252 :                  strcmp(defel->defname, "binary") == 0)
     246             :         {
     247          32 :             if (IsSet(opts->specified_opts, SUBOPT_BINARY))
     248           0 :                 errorConflictingDefElem(defel, pstate);
     249             : 
     250          32 :             opts->specified_opts |= SUBOPT_BINARY;
     251          32 :             opts->binary = defGetBoolean(defel);
     252             :         }
     253         244 :         else if (IsSet(supported_opts, SUBOPT_STREAMING) &&
     254         220 :                  strcmp(defel->defname, "streaming") == 0)
     255             :         {
     256          62 :             if (IsSet(opts->specified_opts, SUBOPT_STREAMING))
     257           0 :                 errorConflictingDefElem(defel, pstate);
     258             : 
     259          62 :             opts->specified_opts |= SUBOPT_STREAMING;
     260          62 :             opts->streaming = defGetStreamingMode(defel);
     261             :         }
     262         182 :         else if (strcmp(defel->defname, "two_phase") == 0)
     263             :         {
     264             :             /*
     265             :              * Do not allow toggling of two_phase option. Doing so could cause
     266             :              * missing of transactions and lead to an inconsistent replica.
     267             :              * See comments atop worker.c
     268             :              *
     269             :              * Note: Unsupported twophase indicates that this call originated
     270             :              * from AlterSubscription.
     271             :              */
     272          38 :             if (!IsSet(supported_opts, SUBOPT_TWOPHASE_COMMIT))
     273           6 :                 ereport(ERROR,
     274             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     275             :                          errmsg("unrecognized subscription parameter: \"%s\"", defel->defname)));
     276             : 
     277          32 :             if (IsSet(opts->specified_opts, SUBOPT_TWOPHASE_COMMIT))
     278           0 :                 errorConflictingDefElem(defel, pstate);
     279             : 
     280          32 :             opts->specified_opts |= SUBOPT_TWOPHASE_COMMIT;
     281          32 :             opts->twophase = defGetBoolean(defel);
     282             :         }
     283         144 :         else if (IsSet(supported_opts, SUBOPT_DISABLE_ON_ERR) &&
     284         120 :                  strcmp(defel->defname, "disable_on_error") == 0)
     285             :         {
     286          20 :             if (IsSet(opts->specified_opts, SUBOPT_DISABLE_ON_ERR))
     287           0 :                 errorConflictingDefElem(defel, pstate);
     288             : 
     289          20 :             opts->specified_opts |= SUBOPT_DISABLE_ON_ERR;
     290          20 :             opts->disableonerr = defGetBoolean(defel);
     291             :         }
     292         124 :         else if (IsSet(supported_opts, SUBOPT_PASSWORD_REQUIRED) &&
     293         100 :                  strcmp(defel->defname, "password_required") == 0)
     294             :         {
     295          24 :             if (IsSet(opts->specified_opts, SUBOPT_PASSWORD_REQUIRED))
     296           0 :                 errorConflictingDefElem(defel, pstate);
     297             : 
     298          24 :             opts->specified_opts |= SUBOPT_PASSWORD_REQUIRED;
     299          24 :             opts->passwordrequired = defGetBoolean(defel);
     300             :         }
     301         100 :         else if (IsSet(supported_opts, SUBOPT_RUN_AS_OWNER) &&
     302          76 :                  strcmp(defel->defname, "run_as_owner") == 0)
     303             :         {
     304          18 :             if (IsSet(opts->specified_opts, SUBOPT_RUN_AS_OWNER))
     305           0 :                 errorConflictingDefElem(defel, pstate);
     306             : 
     307          18 :             opts->specified_opts |= SUBOPT_RUN_AS_OWNER;
     308          18 :             opts->runasowner = defGetBoolean(defel);
     309             :         }
     310          82 :         else if (IsSet(supported_opts, SUBOPT_FAILOVER) &&
     311          58 :                  strcmp(defel->defname, "failover") == 0)
     312             :         {
     313          22 :             if (IsSet(opts->specified_opts, SUBOPT_FAILOVER))
     314           0 :                 errorConflictingDefElem(defel, pstate);
     315             : 
     316          22 :             opts->specified_opts |= SUBOPT_FAILOVER;
     317          22 :             opts->failover = defGetBoolean(defel);
     318             :         }
     319          60 :         else if (IsSet(supported_opts, SUBOPT_ORIGIN) &&
     320          36 :                  strcmp(defel->defname, "origin") == 0)
     321             :         {
     322          30 :             if (IsSet(opts->specified_opts, SUBOPT_ORIGIN))
     323           0 :                 errorConflictingDefElem(defel, pstate);
     324             : 
     325          30 :             opts->specified_opts |= SUBOPT_ORIGIN;
     326          30 :             pfree(opts->origin);
     327             : 
     328             :             /*
     329             :              * Even though the "origin" parameter allows only "none" and "any"
     330             :              * values, it is implemented as a string type so that the
     331             :              * parameter can be extended in future versions to support
     332             :              * filtering using origin names specified by the user.
     333             :              */
     334          30 :             opts->origin = defGetString(defel);
     335             : 
     336          44 :             if ((pg_strcasecmp(opts->origin, LOGICALREP_ORIGIN_NONE) != 0) &&
     337          14 :                 (pg_strcasecmp(opts->origin, LOGICALREP_ORIGIN_ANY) != 0))
     338           6 :                 ereport(ERROR,
     339             :                         errcode(ERRCODE_INVALID_PARAMETER_VALUE),
     340             :                         errmsg("unrecognized origin value: \"%s\"", opts->origin));
     341             :         }
     342          30 :         else if (IsSet(supported_opts, SUBOPT_LSN) &&
     343          24 :                  strcmp(defel->defname, "lsn") == 0)
     344          18 :         {
     345          24 :             char       *lsn_str = defGetString(defel);
     346             :             XLogRecPtr  lsn;
     347             : 
     348          24 :             if (IsSet(opts->specified_opts, SUBOPT_LSN))
     349           0 :                 errorConflictingDefElem(defel, pstate);
     350             : 
     351             :             /* Setting lsn = NONE is treated as resetting LSN */
     352          24 :             if (strcmp(lsn_str, "none") == 0)
     353           6 :                 lsn = InvalidXLogRecPtr;
     354             :             else
     355             :             {
     356             :                 /* Parse the argument as LSN */
     357          18 :                 lsn = DatumGetLSN(DirectFunctionCall1(pg_lsn_in,
     358             :                                                       CStringGetDatum(lsn_str)));
     359             : 
     360          18 :                 if (XLogRecPtrIsInvalid(lsn))
     361           6 :                     ereport(ERROR,
     362             :                             (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
     363             :                              errmsg("invalid WAL location (LSN): %s", lsn_str)));
     364             :             }
     365             : 
     366          18 :             opts->specified_opts |= SUBOPT_LSN;
     367          18 :             opts->lsn = lsn;
     368             :         }
     369             :         else
     370           6 :             ereport(ERROR,
     371             :                     (errcode(ERRCODE_SYNTAX_ERROR),
     372             :                      errmsg("unrecognized subscription parameter: \"%s\"", defel->defname)));
     373             :     }
     374             : 
     375             :     /*
     376             :      * We've been explicitly asked to not connect, that requires some
     377             :      * additional processing.
     378             :      */
     379         764 :     if (!opts->connect && IsSet(supported_opts, SUBOPT_CONNECT))
     380             :     {
     381             :         /* Check for incompatible options from the user. */
     382         132 :         if (opts->enabled &&
     383         132 :             IsSet(opts->specified_opts, SUBOPT_ENABLED))
     384           6 :             ereport(ERROR,
     385             :                     (errcode(ERRCODE_SYNTAX_ERROR),
     386             :             /*- translator: both %s are strings of the form "option = value" */
     387             :                      errmsg("%s and %s are mutually exclusive options",
     388             :                             "connect = false", "enabled = true")));
     389             : 
     390         126 :         if (opts->create_slot &&
     391         120 :             IsSet(opts->specified_opts, SUBOPT_CREATE_SLOT))
     392           6 :             ereport(ERROR,
     393             :                     (errcode(ERRCODE_SYNTAX_ERROR),
     394             :                      errmsg("%s and %s are mutually exclusive options",
     395             :                             "connect = false", "create_slot = true")));
     396             : 
     397         120 :         if (opts->copy_data &&
     398         114 :             IsSet(opts->specified_opts, SUBOPT_COPY_DATA))
     399           6 :             ereport(ERROR,
     400             :                     (errcode(ERRCODE_SYNTAX_ERROR),
     401             :                      errmsg("%s and %s are mutually exclusive options",
     402             :                             "connect = false", "copy_data = true")));
     403             : 
     404             :         /* Change the defaults of other options. */
     405         114 :         opts->enabled = false;
     406         114 :         opts->create_slot = false;
     407         114 :         opts->copy_data = false;
     408             :     }
     409             : 
     410             :     /*
     411             :      * Do additional checking for disallowed combination when slot_name = NONE
     412             :      * was used.
     413             :      */
     414         746 :     if (!opts->slot_name &&
     415         718 :         IsSet(opts->specified_opts, SUBOPT_SLOT_NAME))
     416             :     {
     417         102 :         if (opts->enabled)
     418             :         {
     419          18 :             if (IsSet(opts->specified_opts, SUBOPT_ENABLED))
     420           6 :                 ereport(ERROR,
     421             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     422             :                 /*- translator: both %s are strings of the form "option = value" */
     423             :                          errmsg("%s and %s are mutually exclusive options",
     424             :                                 "slot_name = NONE", "enabled = true")));
     425             :             else
     426          12 :                 ereport(ERROR,
     427             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     428             :                 /*- translator: both %s are strings of the form "option = value" */
     429             :                          errmsg("subscription with %s must also set %s",
     430             :                                 "slot_name = NONE", "enabled = false")));
     431             :         }
     432             : 
     433          84 :         if (opts->create_slot)
     434             :         {
     435          12 :             if (IsSet(opts->specified_opts, SUBOPT_CREATE_SLOT))
     436           6 :                 ereport(ERROR,
     437             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     438             :                 /*- translator: both %s are strings of the form "option = value" */
     439             :                          errmsg("%s and %s are mutually exclusive options",
     440             :                                 "slot_name = NONE", "create_slot = true")));
     441             :             else
     442           6 :                 ereport(ERROR,
     443             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     444             :                 /*- translator: both %s are strings of the form "option = value" */
     445             :                          errmsg("subscription with %s must also set %s",
     446             :                                 "slot_name = NONE", "create_slot = false")));
     447             :         }
     448             :     }
     449         716 : }
     450             : 
     451             : /*
     452             :  * Add publication names from the list to a string.
     453             :  */
     454             : static void
     455         492 : get_publications_str(List *publications, StringInfo dest, bool quote_literal)
     456             : {
     457             :     ListCell   *lc;
     458         492 :     bool        first = true;
     459             : 
     460             :     Assert(publications != NIL);
     461             : 
     462        1140 :     foreach(lc, publications)
     463             :     {
     464         648 :         char       *pubname = strVal(lfirst(lc));
     465             : 
     466         648 :         if (first)
     467         492 :             first = false;
     468             :         else
     469         156 :             appendStringInfoString(dest, ", ");
     470             : 
     471         648 :         if (quote_literal)
     472         636 :             appendStringInfoString(dest, quote_literal_cstr(pubname));
     473             :         else
     474             :         {
     475          12 :             appendStringInfoChar(dest, '"');
     476          12 :             appendStringInfoString(dest, pubname);
     477          12 :             appendStringInfoChar(dest, '"');
     478             :         }
     479             :     }
     480         492 : }
     481             : 
     482             : /*
     483             :  * Check that the specified publications are present on the publisher.
     484             :  */
     485             : static void
     486         214 : check_publications(WalReceiverConn *wrconn, List *publications)
     487             : {
     488             :     WalRcvExecResult *res;
     489             :     StringInfo  cmd;
     490             :     TupleTableSlot *slot;
     491         214 :     List       *publicationsCopy = NIL;
     492         214 :     Oid         tableRow[1] = {TEXTOID};
     493             : 
     494         214 :     cmd = makeStringInfo();
     495         214 :     appendStringInfoString(cmd, "SELECT t.pubname FROM\n"
     496             :                            " pg_catalog.pg_publication t WHERE\n"
     497             :                            " t.pubname IN (");
     498         214 :     get_publications_str(publications, cmd, true);
     499         214 :     appendStringInfoChar(cmd, ')');
     500             : 
     501         214 :     res = walrcv_exec(wrconn, cmd->data, 1, tableRow);
     502         214 :     destroyStringInfo(cmd);
     503             : 
     504         214 :     if (res->status != WALRCV_OK_TUPLES)
     505           0 :         ereport(ERROR,
     506             :                 errmsg("could not receive list of publications from the publisher: %s",
     507             :                        res->err));
     508             : 
     509         214 :     publicationsCopy = list_copy(publications);
     510             : 
     511             :     /* Process publication(s). */
     512         214 :     slot = MakeSingleTupleTableSlot(res->tupledesc, &TTSOpsMinimalTuple);
     513         480 :     while (tuplestore_gettupleslot(res->tuplestore, true, false, slot))
     514             :     {
     515             :         char       *pubname;
     516             :         bool        isnull;
     517             : 
     518         266 :         pubname = TextDatumGetCString(slot_getattr(slot, 1, &isnull));
     519             :         Assert(!isnull);
     520             : 
     521             :         /* Delete the publication present in publisher from the list. */
     522         266 :         publicationsCopy = list_delete(publicationsCopy, makeString(pubname));
     523         266 :         ExecClearTuple(slot);
     524             :     }
     525             : 
     526         214 :     ExecDropSingleTupleTableSlot(slot);
     527             : 
     528         214 :     walrcv_clear_result(res);
     529             : 
     530         214 :     if (list_length(publicationsCopy))
     531             :     {
     532             :         /* Prepare the list of non-existent publication(s) for error message. */
     533           6 :         StringInfo  pubnames = makeStringInfo();
     534             : 
     535           6 :         get_publications_str(publicationsCopy, pubnames, false);
     536           6 :         ereport(WARNING,
     537             :                 errcode(ERRCODE_UNDEFINED_OBJECT),
     538             :                 errmsg_plural("publication %s does not exist on the publisher",
     539             :                               "publications %s do not exist on the publisher",
     540             :                               list_length(publicationsCopy),
     541             :                               pubnames->data));
     542             :     }
     543         214 : }
     544             : 
     545             : /*
     546             :  * Auxiliary function to build a text array out of a list of String nodes.
     547             :  */
     548             : static Datum
     549         336 : publicationListToArray(List *publist)
     550             : {
     551             :     ArrayType  *arr;
     552             :     Datum      *datums;
     553             :     MemoryContext memcxt;
     554             :     MemoryContext oldcxt;
     555             : 
     556             :     /* Create memory context for temporary allocations. */
     557         336 :     memcxt = AllocSetContextCreate(CurrentMemoryContext,
     558             :                                    "publicationListToArray to array",
     559             :                                    ALLOCSET_DEFAULT_SIZES);
     560         336 :     oldcxt = MemoryContextSwitchTo(memcxt);
     561             : 
     562         336 :     datums = (Datum *) palloc(sizeof(Datum) * list_length(publist));
     563             : 
     564         336 :     check_duplicates_in_publist(publist, datums);
     565             : 
     566         330 :     MemoryContextSwitchTo(oldcxt);
     567             : 
     568         330 :     arr = construct_array_builtin(datums, list_length(publist), TEXTOID);
     569             : 
     570         330 :     MemoryContextDelete(memcxt);
     571             : 
     572         330 :     return PointerGetDatum(arr);
     573             : }
     574             : 
     575             : /*
     576             :  * Create new subscription.
     577             :  */
     578             : ObjectAddress
     579         416 : CreateSubscription(ParseState *pstate, CreateSubscriptionStmt *stmt,
     580             :                    bool isTopLevel)
     581             : {
     582             :     Relation    rel;
     583             :     ObjectAddress myself;
     584             :     Oid         subid;
     585             :     bool        nulls[Natts_pg_subscription];
     586             :     Datum       values[Natts_pg_subscription];
     587         416 :     Oid         owner = GetUserId();
     588             :     HeapTuple   tup;
     589             :     char       *conninfo;
     590             :     char        originname[NAMEDATALEN];
     591             :     List       *publications;
     592             :     bits32      supported_opts;
     593         416 :     SubOpts     opts = {0};
     594             :     AclResult   aclresult;
     595             : 
     596             :     /*
     597             :      * Parse and check options.
     598             :      *
     599             :      * Connection and publication should not be specified here.
     600             :      */
     601         416 :     supported_opts = (SUBOPT_CONNECT | SUBOPT_ENABLED | SUBOPT_CREATE_SLOT |
     602             :                       SUBOPT_SLOT_NAME | SUBOPT_COPY_DATA |
     603             :                       SUBOPT_SYNCHRONOUS_COMMIT | SUBOPT_BINARY |
     604             :                       SUBOPT_STREAMING | SUBOPT_TWOPHASE_COMMIT |
     605             :                       SUBOPT_DISABLE_ON_ERR | SUBOPT_PASSWORD_REQUIRED |
     606             :                       SUBOPT_RUN_AS_OWNER | SUBOPT_FAILOVER | SUBOPT_ORIGIN);
     607         416 :     parse_subscription_options(pstate, stmt->options, supported_opts, &opts);
     608             : 
     609             :     /*
     610             :      * Since creating a replication slot is not transactional, rolling back
     611             :      * the transaction leaves the created replication slot.  So we cannot run
     612             :      * CREATE SUBSCRIPTION inside a transaction block if creating a
     613             :      * replication slot.
     614             :      */
     615         338 :     if (opts.create_slot)
     616         214 :         PreventInTransactionBlock(isTopLevel, "CREATE SUBSCRIPTION ... WITH (create_slot = true)");
     617             : 
     618             :     /*
     619             :      * We don't want to allow unprivileged users to be able to trigger
     620             :      * attempts to access arbitrary network destinations, so require the user
     621             :      * to have been specifically authorized to create subscriptions.
     622             :      */
     623         332 :     if (!has_privs_of_role(owner, ROLE_PG_CREATE_SUBSCRIPTION))
     624           6 :         ereport(ERROR,
     625             :                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
     626             :                  errmsg("permission denied to create subscription"),
     627             :                  errdetail("Only roles with privileges of the \"%s\" role may create subscriptions.",
     628             :                            "pg_create_subscription")));
     629             : 
     630             :     /*
     631             :      * Since a subscription is a database object, we also check for CREATE
     632             :      * permission on the database.
     633             :      */
     634         326 :     aclresult = object_aclcheck(DatabaseRelationId, MyDatabaseId,
     635             :                                 owner, ACL_CREATE);
     636         326 :     if (aclresult != ACLCHECK_OK)
     637          12 :         aclcheck_error(aclresult, OBJECT_DATABASE,
     638           6 :                        get_database_name(MyDatabaseId));
     639             : 
     640             :     /*
     641             :      * Non-superusers are required to set a password for authentication, and
     642             :      * that password must be used by the target server, but the superuser can
     643             :      * exempt a subscription from this requirement.
     644             :      */
     645         320 :     if (!opts.passwordrequired && !superuser_arg(owner))
     646           6 :         ereport(ERROR,
     647             :                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
     648             :                  errmsg("password_required=false is superuser-only"),
     649             :                  errhint("Subscriptions with the password_required option set to false may only be created or modified by the superuser.")));
     650             : 
     651             :     /*
     652             :      * If built with appropriate switch, whine when regression-testing
     653             :      * conventions for subscription names are violated.
     654             :      */
     655             : #ifdef ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS
     656             :     if (strncmp(stmt->subname, "regress_", 8) != 0)
     657             :         elog(WARNING, "subscriptions created by regression test cases should have names starting with \"regress_\"");
     658             : #endif
     659             : 
     660         314 :     rel = table_open(SubscriptionRelationId, RowExclusiveLock);
     661             : 
     662             :     /* Check if name is used */
     663         314 :     subid = GetSysCacheOid2(SUBSCRIPTIONNAME, Anum_pg_subscription_oid,
     664             :                             MyDatabaseId, CStringGetDatum(stmt->subname));
     665         314 :     if (OidIsValid(subid))
     666             :     {
     667           6 :         ereport(ERROR,
     668             :                 (errcode(ERRCODE_DUPLICATE_OBJECT),
     669             :                  errmsg("subscription \"%s\" already exists",
     670             :                         stmt->subname)));
     671             :     }
     672             : 
     673         308 :     if (!IsSet(opts.specified_opts, SUBOPT_SLOT_NAME) &&
     674         266 :         opts.slot_name == NULL)
     675         266 :         opts.slot_name = stmt->subname;
     676             : 
     677             :     /* The default for synchronous_commit of subscriptions is off. */
     678         308 :     if (opts.synchronous_commit == NULL)
     679         308 :         opts.synchronous_commit = "off";
     680             : 
     681         308 :     conninfo = stmt->conninfo;
     682         308 :     publications = stmt->publication;
     683             : 
     684             :     /* Load the library providing us libpq calls. */
     685         308 :     load_file("libpqwalreceiver", false);
     686             : 
     687             :     /* Check the connection info string. */
     688         308 :     walrcv_check_conninfo(conninfo, opts.passwordrequired && !superuser());
     689             : 
     690             :     /* Everything ok, form a new tuple. */
     691         290 :     memset(values, 0, sizeof(values));
     692         290 :     memset(nulls, false, sizeof(nulls));
     693             : 
     694         290 :     subid = GetNewOidWithIndex(rel, SubscriptionObjectIndexId,
     695             :                                Anum_pg_subscription_oid);
     696         290 :     values[Anum_pg_subscription_oid - 1] = ObjectIdGetDatum(subid);
     697         290 :     values[Anum_pg_subscription_subdbid - 1] = ObjectIdGetDatum(MyDatabaseId);
     698         290 :     values[Anum_pg_subscription_subskiplsn - 1] = LSNGetDatum(InvalidXLogRecPtr);
     699         290 :     values[Anum_pg_subscription_subname - 1] =
     700         290 :         DirectFunctionCall1(namein, CStringGetDatum(stmt->subname));
     701         290 :     values[Anum_pg_subscription_subowner - 1] = ObjectIdGetDatum(owner);
     702         290 :     values[Anum_pg_subscription_subenabled - 1] = BoolGetDatum(opts.enabled);
     703         290 :     values[Anum_pg_subscription_subbinary - 1] = BoolGetDatum(opts.binary);
     704         290 :     values[Anum_pg_subscription_substream - 1] = CharGetDatum(opts.streaming);
     705         290 :     values[Anum_pg_subscription_subtwophasestate - 1] =
     706         290 :         CharGetDatum(opts.twophase ?
     707             :                      LOGICALREP_TWOPHASE_STATE_PENDING :
     708             :                      LOGICALREP_TWOPHASE_STATE_DISABLED);
     709         290 :     values[Anum_pg_subscription_subdisableonerr - 1] = BoolGetDatum(opts.disableonerr);
     710         290 :     values[Anum_pg_subscription_subpasswordrequired - 1] = BoolGetDatum(opts.passwordrequired);
     711         290 :     values[Anum_pg_subscription_subrunasowner - 1] = BoolGetDatum(opts.runasowner);
     712         290 :     values[Anum_pg_subscription_subfailover - 1] = BoolGetDatum(opts.failover);
     713         290 :     values[Anum_pg_subscription_subconninfo - 1] =
     714         290 :         CStringGetTextDatum(conninfo);
     715         290 :     if (opts.slot_name)
     716         270 :         values[Anum_pg_subscription_subslotname - 1] =
     717         270 :             DirectFunctionCall1(namein, CStringGetDatum(opts.slot_name));
     718             :     else
     719          20 :         nulls[Anum_pg_subscription_subslotname - 1] = true;
     720         290 :     values[Anum_pg_subscription_subsynccommit - 1] =
     721         290 :         CStringGetTextDatum(opts.synchronous_commit);
     722         284 :     values[Anum_pg_subscription_subpublications - 1] =
     723         290 :         publicationListToArray(publications);
     724         284 :     values[Anum_pg_subscription_suborigin - 1] =
     725         284 :         CStringGetTextDatum(opts.origin);
     726             : 
     727         284 :     tup = heap_form_tuple(RelationGetDescr(rel), values, nulls);
     728             : 
     729             :     /* Insert tuple into catalog. */
     730         284 :     CatalogTupleInsert(rel, tup);
     731         284 :     heap_freetuple(tup);
     732             : 
     733         284 :     recordDependencyOnOwner(SubscriptionRelationId, subid, owner);
     734             : 
     735         284 :     ReplicationOriginNameForLogicalRep(subid, InvalidOid, originname, sizeof(originname));
     736         284 :     replorigin_create(originname);
     737             : 
     738             :     /*
     739             :      * Connect to remote side to execute requested commands and fetch table
     740             :      * info.
     741             :      */
     742         284 :     if (opts.connect)
     743             :     {
     744             :         char       *err;
     745             :         WalReceiverConn *wrconn;
     746             :         List       *tables;
     747             :         ListCell   *lc;
     748             :         char        table_state;
     749             :         bool        must_use_password;
     750             : 
     751             :         /* Try to connect to the publisher. */
     752         206 :         must_use_password = !superuser_arg(owner) && opts.passwordrequired;
     753         206 :         wrconn = walrcv_connect(conninfo, true, true, must_use_password,
     754             :                                 stmt->subname, &err);
     755         206 :         if (!wrconn)
     756           6 :             ereport(ERROR,
     757             :                     (errcode(ERRCODE_CONNECTION_FAILURE),
     758             :                      errmsg("could not connect to the publisher: %s", err)));
     759             : 
     760         200 :         PG_TRY();
     761             :         {
     762         200 :             check_publications(wrconn, publications);
     763         200 :             check_publications_origin(wrconn, publications, opts.copy_data,
     764             :                                       opts.origin, NULL, 0, stmt->subname);
     765             : 
     766             :             /*
     767             :              * Set sync state based on if we were asked to do data copy or
     768             :              * not.
     769             :              */
     770         200 :             table_state = opts.copy_data ? SUBREL_STATE_INIT : SUBREL_STATE_READY;
     771             : 
     772             :             /*
     773             :              * Get the table list from publisher and build local table status
     774             :              * info.
     775             :              */
     776         200 :             tables = fetch_table_list(wrconn, publications);
     777         506 :             foreach(lc, tables)
     778             :             {
     779         308 :                 RangeVar   *rv = (RangeVar *) lfirst(lc);
     780             :                 Oid         relid;
     781             : 
     782         308 :                 relid = RangeVarGetRelid(rv, AccessShareLock, false);
     783             : 
     784             :                 /* Check for supported relkind. */
     785         308 :                 CheckSubscriptionRelkind(get_rel_relkind(relid),
     786         308 :                                          rv->schemaname, rv->relname);
     787             : 
     788         308 :                 AddSubscriptionRelState(subid, relid, table_state,
     789             :                                         InvalidXLogRecPtr, true);
     790             :             }
     791             : 
     792             :             /*
     793             :              * If requested, create permanent slot for the subscription. We
     794             :              * won't use the initial snapshot for anything, so no need to
     795             :              * export it.
     796             :              */
     797         198 :             if (opts.create_slot)
     798             :             {
     799         188 :                 bool        twophase_enabled = false;
     800             : 
     801             :                 Assert(opts.slot_name);
     802             : 
     803             :                 /*
     804             :                  * Even if two_phase is set, don't create the slot with
     805             :                  * two-phase enabled. Will enable it once all the tables are
     806             :                  * synced and ready. This avoids race-conditions like prepared
     807             :                  * transactions being skipped due to changes not being applied
     808             :                  * due to checks in should_apply_changes_for_rel() when
     809             :                  * tablesync for the corresponding tables are in progress. See
     810             :                  * comments atop worker.c.
     811             :                  *
     812             :                  * Note that if tables were specified but copy_data is false
     813             :                  * then it is safe to enable two_phase up-front because those
     814             :                  * tables are already initially in READY state. When the
     815             :                  * subscription has no tables, we leave the twophase state as
     816             :                  * PENDING, to allow ALTER SUBSCRIPTION ... REFRESH
     817             :                  * PUBLICATION to work.
     818             :                  */
     819         188 :                 if (opts.twophase && !opts.copy_data && tables != NIL)
     820           2 :                     twophase_enabled = true;
     821             : 
     822         188 :                 walrcv_create_slot(wrconn, opts.slot_name, false, twophase_enabled,
     823             :                                    opts.failover, CRS_NOEXPORT_SNAPSHOT, NULL);
     824             : 
     825         188 :                 if (twophase_enabled)
     826           2 :                     UpdateTwoPhaseState(subid, LOGICALREP_TWOPHASE_STATE_ENABLED);
     827             : 
     828         188 :                 ereport(NOTICE,
     829             :                         (errmsg("created replication slot \"%s\" on publisher",
     830             :                                 opts.slot_name)));
     831             :             }
     832             :         }
     833           2 :         PG_FINALLY();
     834             :         {
     835         200 :             walrcv_disconnect(wrconn);
     836             :         }
     837         200 :         PG_END_TRY();
     838             :     }
     839             :     else
     840          78 :         ereport(WARNING,
     841             :                 (errmsg("subscription was created, but is not connected"),
     842             :                  errhint("To initiate replication, you must manually create the replication slot, enable the subscription, and refresh the subscription.")));
     843             : 
     844         276 :     table_close(rel, RowExclusiveLock);
     845             : 
     846         276 :     pgstat_create_subscription(subid);
     847             : 
     848         276 :     if (opts.enabled)
     849         186 :         ApplyLauncherWakeupAtCommit();
     850             : 
     851         276 :     ObjectAddressSet(myself, SubscriptionRelationId, subid);
     852             : 
     853         276 :     InvokeObjectPostCreateHook(SubscriptionRelationId, subid, 0);
     854             : 
     855         276 :     return myself;
     856             : }
     857             : 
     858             : static void
     859          58 : AlterSubscription_refresh(Subscription *sub, bool copy_data,
     860             :                           List *validate_publications)
     861             : {
     862             :     char       *err;
     863             :     List       *pubrel_names;
     864             :     List       *subrel_states;
     865             :     Oid        *subrel_local_oids;
     866             :     Oid        *pubrel_local_oids;
     867             :     ListCell   *lc;
     868             :     int         off;
     869             :     int         remove_rel_len;
     870             :     int         subrel_count;
     871          58 :     Relation    rel = NULL;
     872             :     typedef struct SubRemoveRels
     873             :     {
     874             :         Oid         relid;
     875             :         char        state;
     876             :     } SubRemoveRels;
     877             :     SubRemoveRels *sub_remove_rels;
     878             :     WalReceiverConn *wrconn;
     879             :     bool        must_use_password;
     880             : 
     881             :     /* Load the library providing us libpq calls. */
     882          58 :     load_file("libpqwalreceiver", false);
     883             : 
     884             :     /* Try to connect to the publisher. */
     885          58 :     must_use_password = sub->passwordrequired && !sub->ownersuperuser;
     886          58 :     wrconn = walrcv_connect(sub->conninfo, true, true, must_use_password,
     887             :                             sub->name, &err);
     888          56 :     if (!wrconn)
     889           0 :         ereport(ERROR,
     890             :                 (errcode(ERRCODE_CONNECTION_FAILURE),
     891             :                  errmsg("could not connect to the publisher: %s", err)));
     892             : 
     893          56 :     PG_TRY();
     894             :     {
     895          56 :         if (validate_publications)
     896          14 :             check_publications(wrconn, validate_publications);
     897             : 
     898             :         /* Get the table list from publisher. */
     899          56 :         pubrel_names = fetch_table_list(wrconn, sub->publications);
     900             : 
     901             :         /* Get local table list. */
     902          56 :         subrel_states = GetSubscriptionRelations(sub->oid, false);
     903          56 :         subrel_count = list_length(subrel_states);
     904             : 
     905             :         /*
     906             :          * Build qsorted array of local table oids for faster lookup. This can
     907             :          * potentially contain all tables in the database so speed of lookup
     908             :          * is important.
     909             :          */
     910          56 :         subrel_local_oids = palloc(subrel_count * sizeof(Oid));
     911          56 :         off = 0;
     912         218 :         foreach(lc, subrel_states)
     913             :         {
     914         162 :             SubscriptionRelState *relstate = (SubscriptionRelState *) lfirst(lc);
     915             : 
     916         162 :             subrel_local_oids[off++] = relstate->relid;
     917             :         }
     918          56 :         qsort(subrel_local_oids, subrel_count,
     919             :               sizeof(Oid), oid_cmp);
     920             : 
     921          56 :         check_publications_origin(wrconn, sub->publications, copy_data,
     922             :                                   sub->origin, subrel_local_oids,
     923             :                                   subrel_count, sub->name);
     924             : 
     925             :         /*
     926             :          * Rels that we want to remove from subscription and drop any slots
     927             :          * and origins corresponding to them.
     928             :          */
     929          56 :         sub_remove_rels = palloc(subrel_count * sizeof(SubRemoveRels));
     930             : 
     931             :         /*
     932             :          * Walk over the remote tables and try to match them to locally known
     933             :          * tables. If the table is not known locally create a new state for
     934             :          * it.
     935             :          *
     936             :          * Also builds array of local oids of remote tables for the next step.
     937             :          */
     938          56 :         off = 0;
     939          56 :         pubrel_local_oids = palloc(list_length(pubrel_names) * sizeof(Oid));
     940             : 
     941         220 :         foreach(lc, pubrel_names)
     942             :         {
     943         164 :             RangeVar   *rv = (RangeVar *) lfirst(lc);
     944             :             Oid         relid;
     945             : 
     946         164 :             relid = RangeVarGetRelid(rv, AccessShareLock, false);
     947             : 
     948             :             /* Check for supported relkind. */
     949         164 :             CheckSubscriptionRelkind(get_rel_relkind(relid),
     950         164 :                                      rv->schemaname, rv->relname);
     951             : 
     952         164 :             pubrel_local_oids[off++] = relid;
     953             : 
     954         164 :             if (!bsearch(&relid, subrel_local_oids,
     955             :                          subrel_count, sizeof(Oid), oid_cmp))
     956             :             {
     957          38 :                 AddSubscriptionRelState(sub->oid, relid,
     958             :                                         copy_data ? SUBREL_STATE_INIT : SUBREL_STATE_READY,
     959             :                                         InvalidXLogRecPtr, true);
     960          38 :                 ereport(DEBUG1,
     961             :                         (errmsg_internal("table \"%s.%s\" added to subscription \"%s\"",
     962             :                                          rv->schemaname, rv->relname, sub->name)));
     963             :             }
     964             :         }
     965             : 
     966             :         /*
     967             :          * Next remove state for tables we should not care about anymore using
     968             :          * the data we collected above
     969             :          */
     970          56 :         qsort(pubrel_local_oids, list_length(pubrel_names),
     971             :               sizeof(Oid), oid_cmp);
     972             : 
     973          56 :         remove_rel_len = 0;
     974         218 :         for (off = 0; off < subrel_count; off++)
     975             :         {
     976         162 :             Oid         relid = subrel_local_oids[off];
     977             : 
     978         162 :             if (!bsearch(&relid, pubrel_local_oids,
     979         162 :                          list_length(pubrel_names), sizeof(Oid), oid_cmp))
     980             :             {
     981             :                 char        state;
     982             :                 XLogRecPtr  statelsn;
     983             : 
     984             :                 /*
     985             :                  * Lock pg_subscription_rel with AccessExclusiveLock to
     986             :                  * prevent any race conditions with the apply worker
     987             :                  * re-launching workers at the same time this code is trying
     988             :                  * to remove those tables.
     989             :                  *
     990             :                  * Even if new worker for this particular rel is restarted it
     991             :                  * won't be able to make any progress as we hold exclusive
     992             :                  * lock on pg_subscription_rel till the transaction end. It
     993             :                  * will simply exit as there is no corresponding rel entry.
     994             :                  *
     995             :                  * This locking also ensures that the state of rels won't
     996             :                  * change till we are done with this refresh operation.
     997             :                  */
     998          36 :                 if (!rel)
     999          14 :                     rel = table_open(SubscriptionRelRelationId, AccessExclusiveLock);
    1000             : 
    1001             :                 /* Last known rel state. */
    1002          36 :                 state = GetSubscriptionRelState(sub->oid, relid, &statelsn);
    1003             : 
    1004          36 :                 sub_remove_rels[remove_rel_len].relid = relid;
    1005          36 :                 sub_remove_rels[remove_rel_len++].state = state;
    1006             : 
    1007          36 :                 RemoveSubscriptionRel(sub->oid, relid);
    1008             : 
    1009          36 :                 logicalrep_worker_stop(sub->oid, relid);
    1010             : 
    1011             :                 /*
    1012             :                  * For READY state, we would have already dropped the
    1013             :                  * tablesync origin.
    1014             :                  */
    1015          36 :                 if (state != SUBREL_STATE_READY)
    1016             :                 {
    1017             :                     char        originname[NAMEDATALEN];
    1018             : 
    1019             :                     /*
    1020             :                      * Drop the tablesync's origin tracking if exists.
    1021             :                      *
    1022             :                      * It is possible that the origin is not yet created for
    1023             :                      * tablesync worker, this can happen for the states before
    1024             :                      * SUBREL_STATE_FINISHEDCOPY. The tablesync worker or
    1025             :                      * apply worker can also concurrently try to drop the
    1026             :                      * origin and by this time the origin might be already
    1027             :                      * removed. For these reasons, passing missing_ok = true.
    1028             :                      */
    1029           0 :                     ReplicationOriginNameForLogicalRep(sub->oid, relid, originname,
    1030             :                                                        sizeof(originname));
    1031           0 :                     replorigin_drop_by_name(originname, true, false);
    1032             :                 }
    1033             : 
    1034          36 :                 ereport(DEBUG1,
    1035             :                         (errmsg_internal("table \"%s.%s\" removed from subscription \"%s\"",
    1036             :                                          get_namespace_name(get_rel_namespace(relid)),
    1037             :                                          get_rel_name(relid),
    1038             :                                          sub->name)));
    1039             :             }
    1040             :         }
    1041             : 
    1042             :         /*
    1043             :          * Drop the tablesync slots associated with removed tables. This has
    1044             :          * to be at the end because otherwise if there is an error while doing
    1045             :          * the database operations we won't be able to rollback dropped slots.
    1046             :          */
    1047          92 :         for (off = 0; off < remove_rel_len; off++)
    1048             :         {
    1049          36 :             if (sub_remove_rels[off].state != SUBREL_STATE_READY &&
    1050           0 :                 sub_remove_rels[off].state != SUBREL_STATE_SYNCDONE)
    1051             :             {
    1052           0 :                 char        syncslotname[NAMEDATALEN] = {0};
    1053             : 
    1054             :                 /*
    1055             :                  * For READY/SYNCDONE states we know the tablesync slot has
    1056             :                  * already been dropped by the tablesync worker.
    1057             :                  *
    1058             :                  * For other states, there is no certainty, maybe the slot
    1059             :                  * does not exist yet. Also, if we fail after removing some of
    1060             :                  * the slots, next time, it will again try to drop already
    1061             :                  * dropped slots and fail. For these reasons, we allow
    1062             :                  * missing_ok = true for the drop.
    1063             :                  */
    1064           0 :                 ReplicationSlotNameForTablesync(sub->oid, sub_remove_rels[off].relid,
    1065             :                                                 syncslotname, sizeof(syncslotname));
    1066           0 :                 ReplicationSlotDropAtPubNode(wrconn, syncslotname, true);
    1067             :             }
    1068             :         }
    1069             :     }
    1070           0 :     PG_FINALLY();
    1071             :     {
    1072          56 :         walrcv_disconnect(wrconn);
    1073             :     }
    1074          56 :     PG_END_TRY();
    1075             : 
    1076          56 :     if (rel)
    1077          14 :         table_close(rel, NoLock);
    1078          56 : }
    1079             : 
    1080             : /*
    1081             :  * Alter the existing subscription.
    1082             :  */
    1083             : ObjectAddress
    1084         440 : AlterSubscription(ParseState *pstate, AlterSubscriptionStmt *stmt,
    1085             :                   bool isTopLevel)
    1086             : {
    1087             :     Relation    rel;
    1088             :     ObjectAddress myself;
    1089             :     bool        nulls[Natts_pg_subscription];
    1090             :     bool        replaces[Natts_pg_subscription];
    1091             :     Datum       values[Natts_pg_subscription];
    1092             :     HeapTuple   tup;
    1093             :     Oid         subid;
    1094         440 :     bool        update_tuple = false;
    1095             :     Subscription *sub;
    1096             :     Form_pg_subscription form;
    1097             :     bits32      supported_opts;
    1098         440 :     SubOpts     opts = {0};
    1099             : 
    1100         440 :     rel = table_open(SubscriptionRelationId, RowExclusiveLock);
    1101             : 
    1102             :     /* Fetch the existing tuple. */
    1103         440 :     tup = SearchSysCacheCopy2(SUBSCRIPTIONNAME, MyDatabaseId,
    1104             :                               CStringGetDatum(stmt->subname));
    1105             : 
    1106         440 :     if (!HeapTupleIsValid(tup))
    1107           6 :         ereport(ERROR,
    1108             :                 (errcode(ERRCODE_UNDEFINED_OBJECT),
    1109             :                  errmsg("subscription \"%s\" does not exist",
    1110             :                         stmt->subname)));
    1111             : 
    1112         434 :     form = (Form_pg_subscription) GETSTRUCT(tup);
    1113         434 :     subid = form->oid;
    1114             : 
    1115             :     /* must be owner */
    1116         434 :     if (!object_ownercheck(SubscriptionRelationId, subid, GetUserId()))
    1117           0 :         aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_SUBSCRIPTION,
    1118           0 :                        stmt->subname);
    1119             : 
    1120         434 :     sub = GetSubscription(subid, false);
    1121             : 
    1122             :     /*
    1123             :      * Don't allow non-superuser modification of a subscription with
    1124             :      * password_required=false.
    1125             :      */
    1126         434 :     if (!sub->passwordrequired && !superuser())
    1127           0 :         ereport(ERROR,
    1128             :                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
    1129             :                  errmsg("password_required=false is superuser-only"),
    1130             :                  errhint("Subscriptions with the password_required option set to false may only be created or modified by the superuser.")));
    1131             : 
    1132             :     /* Lock the subscription so nobody else can do anything with it. */
    1133         434 :     LockSharedObject(SubscriptionRelationId, subid, 0, AccessExclusiveLock);
    1134             : 
    1135             :     /* Form a new tuple. */
    1136         434 :     memset(values, 0, sizeof(values));
    1137         434 :     memset(nulls, false, sizeof(nulls));
    1138         434 :     memset(replaces, false, sizeof(replaces));
    1139             : 
    1140         434 :     switch (stmt->kind)
    1141             :     {
    1142         184 :         case ALTER_SUBSCRIPTION_OPTIONS:
    1143             :             {
    1144         184 :                 supported_opts = (SUBOPT_SLOT_NAME |
    1145             :                                   SUBOPT_SYNCHRONOUS_COMMIT | SUBOPT_BINARY |
    1146             :                                   SUBOPT_STREAMING | SUBOPT_DISABLE_ON_ERR |
    1147             :                                   SUBOPT_PASSWORD_REQUIRED |
    1148             :                                   SUBOPT_RUN_AS_OWNER | SUBOPT_FAILOVER |
    1149             :                                   SUBOPT_ORIGIN);
    1150             : 
    1151         184 :                 parse_subscription_options(pstate, stmt->options,
    1152             :                                            supported_opts, &opts);
    1153             : 
    1154         160 :                 if (IsSet(opts.specified_opts, SUBOPT_SLOT_NAME))
    1155             :                 {
    1156             :                     /*
    1157             :                      * The subscription must be disabled to allow slot_name as
    1158             :                      * 'none', otherwise, the apply worker will repeatedly try
    1159             :                      * to stream the data using that slot_name which neither
    1160             :                      * exists on the publisher nor the user will be allowed to
    1161             :                      * create it.
    1162             :                      */
    1163          58 :                     if (sub->enabled && !opts.slot_name)
    1164           0 :                         ereport(ERROR,
    1165             :                                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    1166             :                                  errmsg("cannot set %s for enabled subscription",
    1167             :                                         "slot_name = NONE")));
    1168             : 
    1169          58 :                     if (opts.slot_name)
    1170           6 :                         values[Anum_pg_subscription_subslotname - 1] =
    1171           6 :                             DirectFunctionCall1(namein, CStringGetDatum(opts.slot_name));
    1172             :                     else
    1173          52 :                         nulls[Anum_pg_subscription_subslotname - 1] = true;
    1174          58 :                     replaces[Anum_pg_subscription_subslotname - 1] = true;
    1175             :                 }
    1176             : 
    1177         160 :                 if (opts.synchronous_commit)
    1178             :                 {
    1179           6 :                     values[Anum_pg_subscription_subsynccommit - 1] =
    1180           6 :                         CStringGetTextDatum(opts.synchronous_commit);
    1181           6 :                     replaces[Anum_pg_subscription_subsynccommit - 1] = true;
    1182             :                 }
    1183             : 
    1184         160 :                 if (IsSet(opts.specified_opts, SUBOPT_BINARY))
    1185             :                 {
    1186          18 :                     values[Anum_pg_subscription_subbinary - 1] =
    1187          18 :                         BoolGetDatum(opts.binary);
    1188          18 :                     replaces[Anum_pg_subscription_subbinary - 1] = true;
    1189             :                 }
    1190             : 
    1191         160 :                 if (IsSet(opts.specified_opts, SUBOPT_STREAMING))
    1192             :                 {
    1193          30 :                     values[Anum_pg_subscription_substream - 1] =
    1194          30 :                         CharGetDatum(opts.streaming);
    1195          30 :                     replaces[Anum_pg_subscription_substream - 1] = true;
    1196             :                 }
    1197             : 
    1198         160 :                 if (IsSet(opts.specified_opts, SUBOPT_DISABLE_ON_ERR))
    1199             :                 {
    1200             :                     values[Anum_pg_subscription_subdisableonerr - 1]
    1201           6 :                         = BoolGetDatum(opts.disableonerr);
    1202             :                     replaces[Anum_pg_subscription_subdisableonerr - 1]
    1203           6 :                         = true;
    1204             :                 }
    1205             : 
    1206         160 :                 if (IsSet(opts.specified_opts, SUBOPT_PASSWORD_REQUIRED))
    1207             :                 {
    1208             :                     /* Non-superuser may not disable password_required. */
    1209          12 :                     if (!opts.passwordrequired && !superuser())
    1210           0 :                         ereport(ERROR,
    1211             :                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
    1212             :                                  errmsg("password_required=false is superuser-only"),
    1213             :                                  errhint("Subscriptions with the password_required option set to false may only be created or modified by the superuser.")));
    1214             : 
    1215             :                     values[Anum_pg_subscription_subpasswordrequired - 1]
    1216          12 :                         = BoolGetDatum(opts.passwordrequired);
    1217             :                     replaces[Anum_pg_subscription_subpasswordrequired - 1]
    1218          12 :                         = true;
    1219             :                 }
    1220             : 
    1221         160 :                 if (IsSet(opts.specified_opts, SUBOPT_RUN_AS_OWNER))
    1222             :                 {
    1223          14 :                     values[Anum_pg_subscription_subrunasowner - 1] =
    1224          14 :                         BoolGetDatum(opts.runasowner);
    1225          14 :                     replaces[Anum_pg_subscription_subrunasowner - 1] = true;
    1226             :                 }
    1227             : 
    1228         160 :                 if (IsSet(opts.specified_opts, SUBOPT_FAILOVER))
    1229             :                 {
    1230          12 :                     if (!sub->slotname)
    1231           0 :                         ereport(ERROR,
    1232             :                                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    1233             :                                  errmsg("cannot set %s for a subscription that does not have a slot name",
    1234             :                                         "failover")));
    1235             : 
    1236             :                     /*
    1237             :                      * Do not allow changing the failover state if the
    1238             :                      * subscription is enabled. This is because the failover
    1239             :                      * state of the slot on the publisher cannot be modified
    1240             :                      * if the slot is currently acquired by the apply worker.
    1241             :                      */
    1242          12 :                     if (sub->enabled)
    1243           2 :                         ereport(ERROR,
    1244             :                                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    1245             :                                  errmsg("cannot set %s for enabled subscription",
    1246             :                                         "failover")));
    1247             : 
    1248             :                     /*
    1249             :                      * The changed failover option of the slot can't be rolled
    1250             :                      * back.
    1251             :                      */
    1252          10 :                     PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION ... SET (failover)");
    1253             : 
    1254           4 :                     values[Anum_pg_subscription_subfailover - 1] =
    1255           4 :                         BoolGetDatum(opts.failover);
    1256           4 :                     replaces[Anum_pg_subscription_subfailover - 1] = true;
    1257             :                 }
    1258             : 
    1259         152 :                 if (IsSet(opts.specified_opts, SUBOPT_ORIGIN))
    1260             :                 {
    1261           6 :                     values[Anum_pg_subscription_suborigin - 1] =
    1262           6 :                         CStringGetTextDatum(opts.origin);
    1263           6 :                     replaces[Anum_pg_subscription_suborigin - 1] = true;
    1264             :                 }
    1265             : 
    1266         152 :                 update_tuple = true;
    1267         152 :                 break;
    1268             :             }
    1269             : 
    1270          70 :         case ALTER_SUBSCRIPTION_ENABLED:
    1271             :             {
    1272          70 :                 parse_subscription_options(pstate, stmt->options,
    1273             :                                            SUBOPT_ENABLED, &opts);
    1274             :                 Assert(IsSet(opts.specified_opts, SUBOPT_ENABLED));
    1275             : 
    1276          70 :                 if (!sub->slotname && opts.enabled)
    1277           6 :                     ereport(ERROR,
    1278             :                             (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    1279             :                              errmsg("cannot enable subscription that does not have a slot name")));
    1280             : 
    1281          64 :                 values[Anum_pg_subscription_subenabled - 1] =
    1282          64 :                     BoolGetDatum(opts.enabled);
    1283          64 :                 replaces[Anum_pg_subscription_subenabled - 1] = true;
    1284             : 
    1285          64 :                 if (opts.enabled)
    1286          38 :                     ApplyLauncherWakeupAtCommit();
    1287             : 
    1288          64 :                 update_tuple = true;
    1289          64 :                 break;
    1290             :             }
    1291             : 
    1292          20 :         case ALTER_SUBSCRIPTION_CONNECTION:
    1293             :             /* Load the library providing us libpq calls. */
    1294          20 :             load_file("libpqwalreceiver", false);
    1295             :             /* Check the connection info string. */
    1296          20 :             walrcv_check_conninfo(stmt->conninfo,
    1297             :                                   sub->passwordrequired && !sub->ownersuperuser);
    1298             : 
    1299          14 :             values[Anum_pg_subscription_subconninfo - 1] =
    1300          14 :                 CStringGetTextDatum(stmt->conninfo);
    1301          14 :             replaces[Anum_pg_subscription_subconninfo - 1] = true;
    1302          14 :             update_tuple = true;
    1303          14 :             break;
    1304             : 
    1305          28 :         case ALTER_SUBSCRIPTION_SET_PUBLICATION:
    1306             :             {
    1307          28 :                 supported_opts = SUBOPT_COPY_DATA | SUBOPT_REFRESH;
    1308          28 :                 parse_subscription_options(pstate, stmt->options,
    1309             :                                            supported_opts, &opts);
    1310             : 
    1311          28 :                 values[Anum_pg_subscription_subpublications - 1] =
    1312          28 :                     publicationListToArray(stmt->publication);
    1313          28 :                 replaces[Anum_pg_subscription_subpublications - 1] = true;
    1314             : 
    1315          28 :                 update_tuple = true;
    1316             : 
    1317             :                 /* Refresh if user asked us to. */
    1318          28 :                 if (opts.refresh)
    1319             :                 {
    1320          22 :                     if (!sub->enabled)
    1321           0 :                         ereport(ERROR,
    1322             :                                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    1323             :                                  errmsg("ALTER SUBSCRIPTION with refresh is not allowed for disabled subscriptions"),
    1324             :                                  errhint("Use ALTER SUBSCRIPTION ... SET PUBLICATION ... WITH (refresh = false).")));
    1325             : 
    1326             :                     /*
    1327             :                      * See ALTER_SUBSCRIPTION_REFRESH for details why this is
    1328             :                      * not allowed.
    1329             :                      */
    1330          22 :                     if (sub->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED && opts.copy_data)
    1331           0 :                         ereport(ERROR,
    1332             :                                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    1333             :                                  errmsg("ALTER SUBSCRIPTION with refresh and copy_data is not allowed when two_phase is enabled"),
    1334             :                                  errhint("Use ALTER SUBSCRIPTION ... SET PUBLICATION with refresh = false, or with copy_data = false, or use DROP/CREATE SUBSCRIPTION.")));
    1335             : 
    1336          22 :                     PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION with refresh");
    1337             : 
    1338             :                     /* Make sure refresh sees the new list of publications. */
    1339          10 :                     sub->publications = stmt->publication;
    1340             : 
    1341          10 :                     AlterSubscription_refresh(sub, opts.copy_data,
    1342             :                                               stmt->publication);
    1343             :                 }
    1344             : 
    1345          16 :                 break;
    1346             :             }
    1347             : 
    1348          54 :         case ALTER_SUBSCRIPTION_ADD_PUBLICATION:
    1349             :         case ALTER_SUBSCRIPTION_DROP_PUBLICATION:
    1350             :             {
    1351             :                 List       *publist;
    1352          54 :                 bool        isadd = stmt->kind == ALTER_SUBSCRIPTION_ADD_PUBLICATION;
    1353             : 
    1354          54 :                 supported_opts = SUBOPT_REFRESH | SUBOPT_COPY_DATA;
    1355          54 :                 parse_subscription_options(pstate, stmt->options,
    1356             :                                            supported_opts, &opts);
    1357             : 
    1358          54 :                 publist = merge_publications(sub->publications, stmt->publication, isadd, stmt->subname);
    1359          18 :                 values[Anum_pg_subscription_subpublications - 1] =
    1360          18 :                     publicationListToArray(publist);
    1361          18 :                 replaces[Anum_pg_subscription_subpublications - 1] = true;
    1362             : 
    1363          18 :                 update_tuple = true;
    1364             : 
    1365             :                 /* Refresh if user asked us to. */
    1366          18 :                 if (opts.refresh)
    1367             :                 {
    1368             :                     /* We only need to validate user specified publications. */
    1369           6 :                     List       *validate_publications = (isadd) ? stmt->publication : NULL;
    1370             : 
    1371           6 :                     if (!sub->enabled)
    1372           0 :                         ereport(ERROR,
    1373             :                                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    1374             :                                  errmsg("ALTER SUBSCRIPTION with refresh is not allowed for disabled subscriptions"),
    1375             :                         /* translator: %s is an SQL ALTER command */
    1376             :                                  errhint("Use %s instead.",
    1377             :                                          isadd ?
    1378             :                                          "ALTER SUBSCRIPTION ... ADD PUBLICATION ... WITH (refresh = false)" :
    1379             :                                          "ALTER SUBSCRIPTION ... DROP PUBLICATION ... WITH (refresh = false)")));
    1380             : 
    1381             :                     /*
    1382             :                      * See ALTER_SUBSCRIPTION_REFRESH for details why this is
    1383             :                      * not allowed.
    1384             :                      */
    1385           6 :                     if (sub->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED && opts.copy_data)
    1386           0 :                         ereport(ERROR,
    1387             :                                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    1388             :                                  errmsg("ALTER SUBSCRIPTION with refresh and copy_data is not allowed when two_phase is enabled"),
    1389             :                         /* translator: %s is an SQL ALTER command */
    1390             :                                  errhint("Use %s with refresh = false, or with copy_data = false, or use DROP/CREATE SUBSCRIPTION.",
    1391             :                                          isadd ?
    1392             :                                          "ALTER SUBSCRIPTION ... ADD PUBLICATION" :
    1393             :                                          "ALTER SUBSCRIPTION ... DROP PUBLICATION")));
    1394             : 
    1395           6 :                     PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION with refresh");
    1396             : 
    1397             :                     /* Refresh the new list of publications. */
    1398           6 :                     sub->publications = publist;
    1399             : 
    1400           6 :                     AlterSubscription_refresh(sub, opts.copy_data,
    1401             :                                               validate_publications);
    1402             :                 }
    1403             : 
    1404          18 :                 break;
    1405             :             }
    1406             : 
    1407          54 :         case ALTER_SUBSCRIPTION_REFRESH:
    1408             :             {
    1409          54 :                 if (!sub->enabled)
    1410           6 :                     ereport(ERROR,
    1411             :                             (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    1412             :                              errmsg("ALTER SUBSCRIPTION ... REFRESH is not allowed for disabled subscriptions")));
    1413             : 
    1414          48 :                 parse_subscription_options(pstate, stmt->options,
    1415             :                                            SUBOPT_COPY_DATA, &opts);
    1416             : 
    1417             :                 /*
    1418             :                  * The subscription option "two_phase" requires that
    1419             :                  * replication has passed the initial table synchronization
    1420             :                  * phase before the two_phase becomes properly enabled.
    1421             :                  *
    1422             :                  * But, having reached this two-phase commit "enabled" state
    1423             :                  * we must not allow any subsequent table initialization to
    1424             :                  * occur. So the ALTER SUBSCRIPTION ... REFRESH is disallowed
    1425             :                  * when the user had requested two_phase = on mode.
    1426             :                  *
    1427             :                  * The exception to this restriction is when copy_data =
    1428             :                  * false, because when copy_data is false the tablesync will
    1429             :                  * start already in READY state and will exit directly without
    1430             :                  * doing anything.
    1431             :                  *
    1432             :                  * For more details see comments atop worker.c.
    1433             :                  */
    1434          48 :                 if (sub->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED && opts.copy_data)
    1435           0 :                     ereport(ERROR,
    1436             :                             (errcode(ERRCODE_SYNTAX_ERROR),
    1437             :                              errmsg("ALTER SUBSCRIPTION ... REFRESH with copy_data is not allowed when two_phase is enabled"),
    1438             :                              errhint("Use ALTER SUBSCRIPTION ... REFRESH with copy_data = false, or use DROP/CREATE SUBSCRIPTION.")));
    1439             : 
    1440          48 :                 PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION ... REFRESH");
    1441             : 
    1442          42 :                 AlterSubscription_refresh(sub, opts.copy_data, NULL);
    1443             : 
    1444          40 :                 break;
    1445             :             }
    1446             : 
    1447          24 :         case ALTER_SUBSCRIPTION_SKIP:
    1448             :             {
    1449          24 :                 parse_subscription_options(pstate, stmt->options, SUBOPT_LSN, &opts);
    1450             : 
    1451             :                 /* ALTER SUBSCRIPTION ... SKIP supports only LSN option */
    1452             :                 Assert(IsSet(opts.specified_opts, SUBOPT_LSN));
    1453             : 
    1454             :                 /*
    1455             :                  * If the user sets subskiplsn, we do a sanity check to make
    1456             :                  * sure that the specified LSN is a probable value.
    1457             :                  */
    1458          18 :                 if (!XLogRecPtrIsInvalid(opts.lsn))
    1459             :                 {
    1460             :                     RepOriginId originid;
    1461             :                     char        originname[NAMEDATALEN];
    1462             :                     XLogRecPtr  remote_lsn;
    1463             : 
    1464          12 :                     ReplicationOriginNameForLogicalRep(subid, InvalidOid,
    1465             :                                                        originname, sizeof(originname));
    1466          12 :                     originid = replorigin_by_name(originname, false);
    1467          12 :                     remote_lsn = replorigin_get_progress(originid, false);
    1468             : 
    1469             :                     /* Check the given LSN is at least a future LSN */
    1470          12 :                     if (!XLogRecPtrIsInvalid(remote_lsn) && opts.lsn < remote_lsn)
    1471           0 :                         ereport(ERROR,
    1472             :                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    1473             :                                  errmsg("skip WAL location (LSN %X/%X) must be greater than origin LSN %X/%X",
    1474             :                                         LSN_FORMAT_ARGS(opts.lsn),
    1475             :                                         LSN_FORMAT_ARGS(remote_lsn))));
    1476             :                 }
    1477             : 
    1478          18 :                 values[Anum_pg_subscription_subskiplsn - 1] = LSNGetDatum(opts.lsn);
    1479          18 :                 replaces[Anum_pg_subscription_subskiplsn - 1] = true;
    1480             : 
    1481          18 :                 update_tuple = true;
    1482          18 :                 break;
    1483             :             }
    1484             : 
    1485           0 :         default:
    1486           0 :             elog(ERROR, "unrecognized ALTER SUBSCRIPTION kind %d",
    1487             :                  stmt->kind);
    1488             :     }
    1489             : 
    1490             :     /* Update the catalog if needed. */
    1491         322 :     if (update_tuple)
    1492             :     {
    1493         282 :         tup = heap_modify_tuple(tup, RelationGetDescr(rel), values, nulls,
    1494             :                                 replaces);
    1495             : 
    1496         282 :         CatalogTupleUpdate(rel, &tup->t_self, tup);
    1497             : 
    1498         282 :         heap_freetuple(tup);
    1499             :     }
    1500             : 
    1501             :     /*
    1502             :      * Try to acquire the connection necessary for altering slot.
    1503             :      *
    1504             :      * This has to be at the end because otherwise if there is an error while
    1505             :      * doing the database operations we won't be able to rollback altered
    1506             :      * slot.
    1507             :      */
    1508         322 :     if (replaces[Anum_pg_subscription_subfailover - 1])
    1509             :     {
    1510             :         bool        must_use_password;
    1511             :         char       *err;
    1512             :         WalReceiverConn *wrconn;
    1513             : 
    1514             :         /* Load the library providing us libpq calls. */
    1515           4 :         load_file("libpqwalreceiver", false);
    1516             : 
    1517             :         /* Try to connect to the publisher. */
    1518           4 :         must_use_password = sub->passwordrequired && !sub->ownersuperuser;
    1519           4 :         wrconn = walrcv_connect(sub->conninfo, true, true, must_use_password,
    1520             :                                 sub->name, &err);
    1521           4 :         if (!wrconn)
    1522           0 :             ereport(ERROR,
    1523             :                     (errcode(ERRCODE_CONNECTION_FAILURE),
    1524             :                      errmsg("could not connect to the publisher: %s", err)));
    1525             : 
    1526           4 :         PG_TRY();
    1527             :         {
    1528           4 :             walrcv_alter_slot(wrconn, sub->slotname, opts.failover);
    1529             :         }
    1530           0 :         PG_FINALLY();
    1531             :         {
    1532           4 :             walrcv_disconnect(wrconn);
    1533             :         }
    1534           4 :         PG_END_TRY();
    1535             :     }
    1536             : 
    1537         322 :     table_close(rel, RowExclusiveLock);
    1538             : 
    1539         322 :     ObjectAddressSet(myself, SubscriptionRelationId, subid);
    1540             : 
    1541         322 :     InvokeObjectPostAlterHook(SubscriptionRelationId, subid, 0);
    1542             : 
    1543             :     /* Wake up related replication workers to handle this change quickly. */
    1544         322 :     LogicalRepWorkersWakeupAtCommit(subid);
    1545             : 
    1546         322 :     return myself;
    1547             : }
    1548             : 
    1549             : /*
    1550             :  * Drop a subscription
    1551             :  */
    1552             : void
    1553         192 : DropSubscription(DropSubscriptionStmt *stmt, bool isTopLevel)
    1554             : {
    1555             :     Relation    rel;
    1556             :     ObjectAddress myself;
    1557             :     HeapTuple   tup;
    1558             :     Oid         subid;
    1559             :     Oid         subowner;
    1560             :     Datum       datum;
    1561             :     bool        isnull;
    1562             :     char       *subname;
    1563             :     char       *conninfo;
    1564             :     char       *slotname;
    1565             :     List       *subworkers;
    1566             :     ListCell   *lc;
    1567             :     char        originname[NAMEDATALEN];
    1568         192 :     char       *err = NULL;
    1569             :     WalReceiverConn *wrconn;
    1570             :     Form_pg_subscription form;
    1571             :     List       *rstates;
    1572             :     bool        must_use_password;
    1573             : 
    1574             :     /*
    1575             :      * Lock pg_subscription with AccessExclusiveLock to ensure that the
    1576             :      * launcher doesn't restart new worker during dropping the subscription
    1577             :      */
    1578         192 :     rel = table_open(SubscriptionRelationId, AccessExclusiveLock);
    1579             : 
    1580         192 :     tup = SearchSysCache2(SUBSCRIPTIONNAME, MyDatabaseId,
    1581         192 :                           CStringGetDatum(stmt->subname));
    1582             : 
    1583         192 :     if (!HeapTupleIsValid(tup))
    1584             :     {
    1585          12 :         table_close(rel, NoLock);
    1586             : 
    1587          12 :         if (!stmt->missing_ok)
    1588           6 :             ereport(ERROR,
    1589             :                     (errcode(ERRCODE_UNDEFINED_OBJECT),
    1590             :                      errmsg("subscription \"%s\" does not exist",
    1591             :                             stmt->subname)));
    1592             :         else
    1593           6 :             ereport(NOTICE,
    1594             :                     (errmsg("subscription \"%s\" does not exist, skipping",
    1595             :                             stmt->subname)));
    1596             : 
    1597          78 :         return;
    1598             :     }
    1599             : 
    1600         180 :     form = (Form_pg_subscription) GETSTRUCT(tup);
    1601         180 :     subid = form->oid;
    1602         180 :     subowner = form->subowner;
    1603         180 :     must_use_password = !superuser_arg(subowner) && form->subpasswordrequired;
    1604             : 
    1605             :     /* must be owner */
    1606         180 :     if (!object_ownercheck(SubscriptionRelationId, subid, GetUserId()))
    1607           0 :         aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_SUBSCRIPTION,
    1608           0 :                        stmt->subname);
    1609             : 
    1610             :     /* DROP hook for the subscription being removed */
    1611         180 :     InvokeObjectDropHook(SubscriptionRelationId, subid, 0);
    1612             : 
    1613             :     /*
    1614             :      * Lock the subscription so nobody else can do anything with it (including
    1615             :      * the replication workers).
    1616             :      */
    1617         180 :     LockSharedObject(SubscriptionRelationId, subid, 0, AccessExclusiveLock);
    1618             : 
    1619             :     /* Get subname */
    1620         180 :     datum = SysCacheGetAttrNotNull(SUBSCRIPTIONOID, tup,
    1621             :                                    Anum_pg_subscription_subname);
    1622         180 :     subname = pstrdup(NameStr(*DatumGetName(datum)));
    1623             : 
    1624             :     /* Get conninfo */
    1625         180 :     datum = SysCacheGetAttrNotNull(SUBSCRIPTIONOID, tup,
    1626             :                                    Anum_pg_subscription_subconninfo);
    1627         180 :     conninfo = TextDatumGetCString(datum);
    1628             : 
    1629             :     /* Get slotname */
    1630         180 :     datum = SysCacheGetAttr(SUBSCRIPTIONOID, tup,
    1631             :                             Anum_pg_subscription_subslotname, &isnull);
    1632         180 :     if (!isnull)
    1633         108 :         slotname = pstrdup(NameStr(*DatumGetName(datum)));
    1634             :     else
    1635          72 :         slotname = NULL;
    1636             : 
    1637             :     /*
    1638             :      * Since dropping a replication slot is not transactional, the replication
    1639             :      * slot stays dropped even if the transaction rolls back.  So we cannot
    1640             :      * run DROP SUBSCRIPTION inside a transaction block if dropping the
    1641             :      * replication slot.  Also, in this case, we report a message for dropping
    1642             :      * the subscription to the cumulative stats system.
    1643             :      *
    1644             :      * XXX The command name should really be something like "DROP SUBSCRIPTION
    1645             :      * of a subscription that is associated with a replication slot", but we
    1646             :      * don't have the proper facilities for that.
    1647             :      */
    1648         180 :     if (slotname)
    1649         108 :         PreventInTransactionBlock(isTopLevel, "DROP SUBSCRIPTION");
    1650             : 
    1651         174 :     ObjectAddressSet(myself, SubscriptionRelationId, subid);
    1652         174 :     EventTriggerSQLDropAddObject(&myself, true, true);
    1653             : 
    1654             :     /* Remove the tuple from catalog. */
    1655         174 :     CatalogTupleDelete(rel, &tup->t_self);
    1656             : 
    1657         174 :     ReleaseSysCache(tup);
    1658             : 
    1659             :     /*
    1660             :      * Stop all the subscription workers immediately.
    1661             :      *
    1662             :      * This is necessary if we are dropping the replication slot, so that the
    1663             :      * slot becomes accessible.
    1664             :      *
    1665             :      * It is also necessary if the subscription is disabled and was disabled
    1666             :      * in the same transaction.  Then the workers haven't seen the disabling
    1667             :      * yet and will still be running, leading to hangs later when we want to
    1668             :      * drop the replication origin.  If the subscription was disabled before
    1669             :      * this transaction, then there shouldn't be any workers left, so this
    1670             :      * won't make a difference.
    1671             :      *
    1672             :      * New workers won't be started because we hold an exclusive lock on the
    1673             :      * subscription till the end of the transaction.
    1674             :      */
    1675         174 :     LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
    1676         174 :     subworkers = logicalrep_workers_find(subid, false);
    1677         174 :     LWLockRelease(LogicalRepWorkerLock);
    1678         282 :     foreach(lc, subworkers)
    1679             :     {
    1680         108 :         LogicalRepWorker *w = (LogicalRepWorker *) lfirst(lc);
    1681             : 
    1682         108 :         logicalrep_worker_stop(w->subid, w->relid);
    1683             :     }
    1684         174 :     list_free(subworkers);
    1685             : 
    1686             :     /*
    1687             :      * Remove the no-longer-useful entry in the launcher's table of apply
    1688             :      * worker start times.
    1689             :      *
    1690             :      * If this transaction rolls back, the launcher might restart a failed
    1691             :      * apply worker before wal_retrieve_retry_interval milliseconds have
    1692             :      * elapsed, but that's pretty harmless.
    1693             :      */
    1694         174 :     ApplyLauncherForgetWorkerStartTime(subid);
    1695             : 
    1696             :     /*
    1697             :      * Cleanup of tablesync replication origins.
    1698             :      *
    1699             :      * Any READY-state relations would already have dealt with clean-ups.
    1700             :      *
    1701             :      * Note that the state can't change because we have already stopped both
    1702             :      * the apply and tablesync workers and they can't restart because of
    1703             :      * exclusive lock on the subscription.
    1704             :      */
    1705         174 :     rstates = GetSubscriptionRelations(subid, true);
    1706         178 :     foreach(lc, rstates)
    1707             :     {
    1708           4 :         SubscriptionRelState *rstate = (SubscriptionRelState *) lfirst(lc);
    1709           4 :         Oid         relid = rstate->relid;
    1710             : 
    1711             :         /* Only cleanup resources of tablesync workers */
    1712           4 :         if (!OidIsValid(relid))
    1713           0 :             continue;
    1714             : 
    1715             :         /*
    1716             :          * Drop the tablesync's origin tracking if exists.
    1717             :          *
    1718             :          * It is possible that the origin is not yet created for tablesync
    1719             :          * worker so passing missing_ok = true. This can happen for the states
    1720             :          * before SUBREL_STATE_FINISHEDCOPY.
    1721             :          */
    1722           4 :         ReplicationOriginNameForLogicalRep(subid, relid, originname,
    1723             :                                            sizeof(originname));
    1724           4 :         replorigin_drop_by_name(originname, true, false);
    1725             :     }
    1726             : 
    1727             :     /* Clean up dependencies */
    1728         174 :     deleteSharedDependencyRecordsFor(SubscriptionRelationId, subid, 0);
    1729             : 
    1730             :     /* Remove any associated relation synchronization states. */
    1731         174 :     RemoveSubscriptionRel(subid, InvalidOid);
    1732             : 
    1733             :     /* Remove the origin tracking if exists. */
    1734         174 :     ReplicationOriginNameForLogicalRep(subid, InvalidOid, originname, sizeof(originname));
    1735         174 :     replorigin_drop_by_name(originname, true, false);
    1736             : 
    1737             :     /*
    1738             :      * Tell the cumulative stats system that the subscription is getting
    1739             :      * dropped.
    1740             :      */
    1741         174 :     pgstat_drop_subscription(subid);
    1742             : 
    1743             :     /*
    1744             :      * If there is no slot associated with the subscription, we can finish
    1745             :      * here.
    1746             :      */
    1747         174 :     if (!slotname && rstates == NIL)
    1748             :     {
    1749          72 :         table_close(rel, NoLock);
    1750          72 :         return;
    1751             :     }
    1752             : 
    1753             :     /*
    1754             :      * Try to acquire the connection necessary for dropping slots.
    1755             :      *
    1756             :      * Note: If the slotname is NONE/NULL then we allow the command to finish
    1757             :      * and users need to manually cleanup the apply and tablesync worker slots
    1758             :      * later.
    1759             :      *
    1760             :      * This has to be at the end because otherwise if there is an error while
    1761             :      * doing the database operations we won't be able to rollback dropped
    1762             :      * slot.
    1763             :      */
    1764         102 :     load_file("libpqwalreceiver", false);
    1765             : 
    1766         102 :     wrconn = walrcv_connect(conninfo, true, true, must_use_password,
    1767             :                             subname, &err);
    1768         102 :     if (wrconn == NULL)
    1769             :     {
    1770           0 :         if (!slotname)
    1771             :         {
    1772             :             /* be tidy */
    1773           0 :             list_free(rstates);
    1774           0 :             table_close(rel, NoLock);
    1775           0 :             return;
    1776             :         }
    1777             :         else
    1778             :         {
    1779           0 :             ReportSlotConnectionError(rstates, subid, slotname, err);
    1780             :         }
    1781             :     }
    1782             : 
    1783         102 :     PG_TRY();
    1784             :     {
    1785         106 :         foreach(lc, rstates)
    1786             :         {
    1787           4 :             SubscriptionRelState *rstate = (SubscriptionRelState *) lfirst(lc);
    1788           4 :             Oid         relid = rstate->relid;
    1789             : 
    1790             :             /* Only cleanup resources of tablesync workers */
    1791           4 :             if (!OidIsValid(relid))
    1792           0 :                 continue;
    1793             : 
    1794             :             /*
    1795             :              * Drop the tablesync slots associated with removed tables.
    1796             :              *
    1797             :              * For SYNCDONE/READY states, the tablesync slot is known to have
    1798             :              * already been dropped by the tablesync worker.
    1799             :              *
    1800             :              * For other states, there is no certainty, maybe the slot does
    1801             :              * not exist yet. Also, if we fail after removing some of the
    1802             :              * slots, next time, it will again try to drop already dropped
    1803             :              * slots and fail. For these reasons, we allow missing_ok = true
    1804             :              * for the drop.
    1805             :              */
    1806           4 :             if (rstate->state != SUBREL_STATE_SYNCDONE)
    1807             :             {
    1808           4 :                 char        syncslotname[NAMEDATALEN] = {0};
    1809             : 
    1810           4 :                 ReplicationSlotNameForTablesync(subid, relid, syncslotname,
    1811             :                                                 sizeof(syncslotname));
    1812           4 :                 ReplicationSlotDropAtPubNode(wrconn, syncslotname, true);
    1813             :             }
    1814             :         }
    1815             : 
    1816         102 :         list_free(rstates);
    1817             : 
    1818             :         /*
    1819             :          * If there is a slot associated with the subscription, then drop the
    1820             :          * replication slot at the publisher.
    1821             :          */
    1822         102 :         if (slotname)
    1823         102 :             ReplicationSlotDropAtPubNode(wrconn, slotname, false);
    1824             :     }
    1825           0 :     PG_FINALLY();
    1826             :     {
    1827         102 :         walrcv_disconnect(wrconn);
    1828             :     }
    1829         102 :     PG_END_TRY();
    1830             : 
    1831         102 :     table_close(rel, NoLock);
    1832             : }
    1833             : 
    1834             : /*
    1835             :  * Drop the replication slot at the publisher node using the replication
    1836             :  * connection.
    1837             :  *
    1838             :  * missing_ok - if true then only issue a LOG message if the slot doesn't
    1839             :  * exist.
    1840             :  */
    1841             : void
    1842         446 : ReplicationSlotDropAtPubNode(WalReceiverConn *wrconn, char *slotname, bool missing_ok)
    1843             : {
    1844             :     StringInfoData cmd;
    1845             : 
    1846             :     Assert(wrconn);
    1847             : 
    1848         446 :     load_file("libpqwalreceiver", false);
    1849             : 
    1850         446 :     initStringInfo(&cmd);
    1851         446 :     appendStringInfo(&cmd, "DROP_REPLICATION_SLOT %s WAIT", quote_identifier(slotname));
    1852             : 
    1853         446 :     PG_TRY();
    1854             :     {
    1855             :         WalRcvExecResult *res;
    1856             : 
    1857         446 :         res = walrcv_exec(wrconn, cmd.data, 0, NULL);
    1858             : 
    1859         446 :         if (res->status == WALRCV_OK_COMMAND)
    1860             :         {
    1861             :             /* NOTICE. Success. */
    1862         444 :             ereport(NOTICE,
    1863             :                     (errmsg("dropped replication slot \"%s\" on publisher",
    1864             :                             slotname)));
    1865             :         }
    1866           2 :         else if (res->status == WALRCV_ERROR &&
    1867           2 :                  missing_ok &&
    1868           2 :                  res->sqlstate == ERRCODE_UNDEFINED_OBJECT)
    1869             :         {
    1870             :             /* LOG. Error, but missing_ok = true. */
    1871           2 :             ereport(LOG,
    1872             :                     (errmsg("could not drop replication slot \"%s\" on publisher: %s",
    1873             :                             slotname, res->err)));
    1874             :         }
    1875             :         else
    1876             :         {
    1877             :             /* ERROR. */
    1878           0 :             ereport(ERROR,
    1879             :                     (errcode(ERRCODE_CONNECTION_FAILURE),
    1880             :                      errmsg("could not drop replication slot \"%s\" on publisher: %s",
    1881             :                             slotname, res->err)));
    1882             :         }
    1883             : 
    1884         446 :         walrcv_clear_result(res);
    1885             :     }
    1886           0 :     PG_FINALLY();
    1887             :     {
    1888         446 :         pfree(cmd.data);
    1889             :     }
    1890         446 :     PG_END_TRY();
    1891         446 : }
    1892             : 
    1893             : /*
    1894             :  * Internal workhorse for changing a subscription owner
    1895             :  */
    1896             : static void
    1897          18 : AlterSubscriptionOwner_internal(Relation rel, HeapTuple tup, Oid newOwnerId)
    1898             : {
    1899             :     Form_pg_subscription form;
    1900             :     AclResult   aclresult;
    1901             : 
    1902          18 :     form = (Form_pg_subscription) GETSTRUCT(tup);
    1903             : 
    1904          18 :     if (form->subowner == newOwnerId)
    1905           4 :         return;
    1906             : 
    1907          14 :     if (!object_ownercheck(SubscriptionRelationId, form->oid, GetUserId()))
    1908           0 :         aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_SUBSCRIPTION,
    1909           0 :                        NameStr(form->subname));
    1910             : 
    1911             :     /*
    1912             :      * Don't allow non-superuser modification of a subscription with
    1913             :      * password_required=false.
    1914             :      */
    1915          14 :     if (!form->subpasswordrequired && !superuser())
    1916           0 :         ereport(ERROR,
    1917             :                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
    1918             :                  errmsg("password_required=false is superuser-only"),
    1919             :                  errhint("Subscriptions with the password_required option set to false may only be created or modified by the superuser.")));
    1920             : 
    1921             :     /* Must be able to become new owner */
    1922          14 :     check_can_set_role(GetUserId(), newOwnerId);
    1923             : 
    1924             :     /*
    1925             :      * current owner must have CREATE on database
    1926             :      *
    1927             :      * This is consistent with how ALTER SCHEMA ... OWNER TO works, but some
    1928             :      * other object types behave differently (e.g. you can't give a table to a
    1929             :      * user who lacks CREATE privileges on a schema).
    1930             :      */
    1931           8 :     aclresult = object_aclcheck(DatabaseRelationId, MyDatabaseId,
    1932             :                                 GetUserId(), ACL_CREATE);
    1933           8 :     if (aclresult != ACLCHECK_OK)
    1934           0 :         aclcheck_error(aclresult, OBJECT_DATABASE,
    1935           0 :                        get_database_name(MyDatabaseId));
    1936             : 
    1937           8 :     form->subowner = newOwnerId;
    1938           8 :     CatalogTupleUpdate(rel, &tup->t_self, tup);
    1939             : 
    1940             :     /* Update owner dependency reference */
    1941           8 :     changeDependencyOnOwner(SubscriptionRelationId,
    1942             :                             form->oid,
    1943             :                             newOwnerId);
    1944             : 
    1945           8 :     InvokeObjectPostAlterHook(SubscriptionRelationId,
    1946             :                               form->oid, 0);
    1947             : 
    1948             :     /* Wake up related background processes to handle this change quickly. */
    1949           8 :     ApplyLauncherWakeupAtCommit();
    1950           8 :     LogicalRepWorkersWakeupAtCommit(form->oid);
    1951             : }
    1952             : 
    1953             : /*
    1954             :  * Change subscription owner -- by name
    1955             :  */
    1956             : ObjectAddress
    1957          18 : AlterSubscriptionOwner(const char *name, Oid newOwnerId)
    1958             : {
    1959             :     Oid         subid;
    1960             :     HeapTuple   tup;
    1961             :     Relation    rel;
    1962             :     ObjectAddress address;
    1963             :     Form_pg_subscription form;
    1964             : 
    1965          18 :     rel = table_open(SubscriptionRelationId, RowExclusiveLock);
    1966             : 
    1967          18 :     tup = SearchSysCacheCopy2(SUBSCRIPTIONNAME, MyDatabaseId,
    1968             :                               CStringGetDatum(name));
    1969             : 
    1970          18 :     if (!HeapTupleIsValid(tup))
    1971           0 :         ereport(ERROR,
    1972             :                 (errcode(ERRCODE_UNDEFINED_OBJECT),
    1973             :                  errmsg("subscription \"%s\" does not exist", name)));
    1974             : 
    1975          18 :     form = (Form_pg_subscription) GETSTRUCT(tup);
    1976          18 :     subid = form->oid;
    1977             : 
    1978          18 :     AlterSubscriptionOwner_internal(rel, tup, newOwnerId);
    1979             : 
    1980          12 :     ObjectAddressSet(address, SubscriptionRelationId, subid);
    1981             : 
    1982          12 :     heap_freetuple(tup);
    1983             : 
    1984          12 :     table_close(rel, RowExclusiveLock);
    1985             : 
    1986          12 :     return address;
    1987             : }
    1988             : 
    1989             : /*
    1990             :  * Change subscription owner -- by OID
    1991             :  */
    1992             : void
    1993           0 : AlterSubscriptionOwner_oid(Oid subid, Oid newOwnerId)
    1994             : {
    1995             :     HeapTuple   tup;
    1996             :     Relation    rel;
    1997             : 
    1998           0 :     rel = table_open(SubscriptionRelationId, RowExclusiveLock);
    1999             : 
    2000           0 :     tup = SearchSysCacheCopy1(SUBSCRIPTIONOID, ObjectIdGetDatum(subid));
    2001             : 
    2002           0 :     if (!HeapTupleIsValid(tup))
    2003           0 :         ereport(ERROR,
    2004             :                 (errcode(ERRCODE_UNDEFINED_OBJECT),
    2005             :                  errmsg("subscription with OID %u does not exist", subid)));
    2006             : 
    2007           0 :     AlterSubscriptionOwner_internal(rel, tup, newOwnerId);
    2008             : 
    2009           0 :     heap_freetuple(tup);
    2010             : 
    2011           0 :     table_close(rel, RowExclusiveLock);
    2012           0 : }
    2013             : 
    2014             : /*
    2015             :  * Check and log a warning if the publisher has subscribed to the same table
    2016             :  * from some other publisher. This check is required only if "copy_data = true"
    2017             :  * and "origin = none" for CREATE SUBSCRIPTION and
    2018             :  * ALTER SUBSCRIPTION ... REFRESH statements to notify the user that data
    2019             :  * having origin might have been copied.
    2020             :  *
    2021             :  * This check need not be performed on the tables that are already added
    2022             :  * because incremental sync for those tables will happen through WAL and the
    2023             :  * origin of the data can be identified from the WAL records.
    2024             :  *
    2025             :  * subrel_local_oids contains the list of relation oids that are already
    2026             :  * present on the subscriber.
    2027             :  */
    2028             : static void
    2029         256 : check_publications_origin(WalReceiverConn *wrconn, List *publications,
    2030             :                           bool copydata, char *origin, Oid *subrel_local_oids,
    2031             :                           int subrel_count, char *subname)
    2032             : {
    2033             :     WalRcvExecResult *res;
    2034             :     StringInfoData cmd;
    2035             :     TupleTableSlot *slot;
    2036         256 :     Oid         tableRow[1] = {TEXTOID};
    2037         256 :     List       *publist = NIL;
    2038             :     int         i;
    2039             : 
    2040         490 :     if (!copydata || !origin ||
    2041         234 :         (pg_strcasecmp(origin, LOGICALREP_ORIGIN_NONE) != 0))
    2042         244 :         return;
    2043             : 
    2044          12 :     initStringInfo(&cmd);
    2045          12 :     appendStringInfoString(&cmd,
    2046             :                            "SELECT DISTINCT P.pubname AS pubname\n"
    2047             :                            "FROM pg_publication P,\n"
    2048             :                            "     LATERAL pg_get_publication_tables(P.pubname) GPT\n"
    2049             :                            "     JOIN pg_subscription_rel PS ON (GPT.relid = PS.srrelid),\n"
    2050             :                            "     pg_class C JOIN pg_namespace N ON (N.oid = C.relnamespace)\n"
    2051             :                            "WHERE C.oid = GPT.relid AND P.pubname IN (");
    2052          12 :     get_publications_str(publications, &cmd, true);
    2053          12 :     appendStringInfoString(&cmd, ")\n");
    2054             : 
    2055             :     /*
    2056             :      * In case of ALTER SUBSCRIPTION ... REFRESH, subrel_local_oids contains
    2057             :      * the list of relation oids that are already present on the subscriber.
    2058             :      * This check should be skipped for these tables.
    2059             :      */
    2060          18 :     for (i = 0; i < subrel_count; i++)
    2061             :     {
    2062           6 :         Oid         relid = subrel_local_oids[i];
    2063           6 :         char       *schemaname = get_namespace_name(get_rel_namespace(relid));
    2064           6 :         char       *tablename = get_rel_name(relid);
    2065             : 
    2066           6 :         appendStringInfo(&cmd, "AND NOT (N.nspname = '%s' AND C.relname = '%s')\n",
    2067             :                          schemaname, tablename);
    2068             :     }
    2069             : 
    2070          12 :     res = walrcv_exec(wrconn, cmd.data, 1, tableRow);
    2071          12 :     pfree(cmd.data);
    2072             : 
    2073          12 :     if (res->status != WALRCV_OK_TUPLES)
    2074           0 :         ereport(ERROR,
    2075             :                 (errcode(ERRCODE_CONNECTION_FAILURE),
    2076             :                  errmsg("could not receive list of replicated tables from the publisher: %s",
    2077             :                         res->err)));
    2078             : 
    2079             :     /* Process tables. */
    2080          12 :     slot = MakeSingleTupleTableSlot(res->tupledesc, &TTSOpsMinimalTuple);
    2081          16 :     while (tuplestore_gettupleslot(res->tuplestore, true, false, slot))
    2082             :     {
    2083             :         char       *pubname;
    2084             :         bool        isnull;
    2085             : 
    2086           4 :         pubname = TextDatumGetCString(slot_getattr(slot, 1, &isnull));
    2087             :         Assert(!isnull);
    2088             : 
    2089           4 :         ExecClearTuple(slot);
    2090           4 :         publist = list_append_unique(publist, makeString(pubname));
    2091             :     }
    2092             : 
    2093             :     /*
    2094             :      * Log a warning if the publisher has subscribed to the same table from
    2095             :      * some other publisher. We cannot know the origin of data during the
    2096             :      * initial sync. Data origins can be found only from the WAL by looking at
    2097             :      * the origin id.
    2098             :      *
    2099             :      * XXX: For simplicity, we don't check whether the table has any data or
    2100             :      * not. If the table doesn't have any data then we don't need to
    2101             :      * distinguish between data having origin and data not having origin so we
    2102             :      * can avoid logging a warning in that case.
    2103             :      */
    2104          12 :     if (publist)
    2105             :     {
    2106           4 :         StringInfo  pubnames = makeStringInfo();
    2107             : 
    2108             :         /* Prepare the list of publication(s) for warning message. */
    2109           4 :         get_publications_str(publist, pubnames, false);
    2110           4 :         ereport(WARNING,
    2111             :                 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    2112             :                 errmsg("subscription \"%s\" requested copy_data with origin = NONE but might copy data that had a different origin",
    2113             :                        subname),
    2114             :                 errdetail_plural("The subscription being created subscribes to a publication (%s) that contains tables that are written to by other subscriptions.",
    2115             :                                  "The subscription being created subscribes to publications (%s) that contain tables that are written to by other subscriptions.",
    2116             :                                  list_length(publist), pubnames->data),
    2117             :                 errhint("Verify that initial data copied from the publisher tables did not come from other origins."));
    2118             :     }
    2119             : 
    2120          12 :     ExecDropSingleTupleTableSlot(slot);
    2121             : 
    2122          12 :     walrcv_clear_result(res);
    2123             : }
    2124             : 
    2125             : /*
    2126             :  * Get the list of tables which belong to specified publications on the
    2127             :  * publisher connection.
    2128             :  *
    2129             :  * Note that we don't support the case where the column list is different for
    2130             :  * the same table in different publications to avoid sending unwanted column
    2131             :  * information for some of the rows. This can happen when both the column
    2132             :  * list and row filter are specified for different publications.
    2133             :  */
    2134             : static List *
    2135         256 : fetch_table_list(WalReceiverConn *wrconn, List *publications)
    2136             : {
    2137             :     WalRcvExecResult *res;
    2138             :     StringInfoData cmd;
    2139             :     TupleTableSlot *slot;
    2140         256 :     Oid         tableRow[3] = {TEXTOID, TEXTOID, InvalidOid};
    2141         256 :     List       *tablelist = NIL;
    2142         256 :     int         server_version = walrcv_server_version(wrconn);
    2143         256 :     bool        check_columnlist = (server_version >= 150000);
    2144             : 
    2145         256 :     initStringInfo(&cmd);
    2146             : 
    2147             :     /* Get the list of tables from the publisher. */
    2148         256 :     if (server_version >= 160000)
    2149             :     {
    2150             :         StringInfoData pub_names;
    2151             : 
    2152         256 :         tableRow[2] = INT2VECTOROID;
    2153         256 :         initStringInfo(&pub_names);
    2154         256 :         get_publications_str(publications, &pub_names, true);
    2155             : 
    2156             :         /*
    2157             :          * From version 16, we allowed passing multiple publications to the
    2158             :          * function pg_get_publication_tables. This helped to filter out the
    2159             :          * partition table whose ancestor is also published in this
    2160             :          * publication array.
    2161             :          *
    2162             :          * Join pg_get_publication_tables with pg_publication to exclude
    2163             :          * non-existing publications.
    2164             :          *
    2165             :          * Note that attrs are always stored in sorted order so we don't need
    2166             :          * to worry if different publications have specified them in a
    2167             :          * different order. See publication_translate_columns.
    2168             :          */
    2169         256 :         appendStringInfo(&cmd, "SELECT DISTINCT n.nspname, c.relname, gpt.attrs\n"
    2170             :                          "       FROM pg_class c\n"
    2171             :                          "         JOIN pg_namespace n ON n.oid = c.relnamespace\n"
    2172             :                          "         JOIN ( SELECT (pg_get_publication_tables(VARIADIC array_agg(pubname::text))).*\n"
    2173             :                          "                FROM pg_publication\n"
    2174             :                          "                WHERE pubname IN ( %s )) AS gpt\n"
    2175             :                          "             ON gpt.relid = c.oid\n",
    2176             :                          pub_names.data);
    2177             : 
    2178         256 :         pfree(pub_names.data);
    2179             :     }
    2180             :     else
    2181             :     {
    2182           0 :         tableRow[2] = NAMEARRAYOID;
    2183           0 :         appendStringInfoString(&cmd, "SELECT DISTINCT t.schemaname, t.tablename \n");
    2184             : 
    2185             :         /* Get column lists for each relation if the publisher supports it */
    2186           0 :         if (check_columnlist)
    2187           0 :             appendStringInfoString(&cmd, ", t.attnames\n");
    2188             : 
    2189           0 :         appendStringInfoString(&cmd, "FROM pg_catalog.pg_publication_tables t\n"
    2190             :                                " WHERE t.pubname IN (");
    2191           0 :         get_publications_str(publications, &cmd, true);
    2192           0 :         appendStringInfoChar(&cmd, ')');
    2193             :     }
    2194             : 
    2195         256 :     res = walrcv_exec(wrconn, cmd.data, check_columnlist ? 3 : 2, tableRow);
    2196         256 :     pfree(cmd.data);
    2197             : 
    2198         256 :     if (res->status != WALRCV_OK_TUPLES)
    2199           0 :         ereport(ERROR,
    2200             :                 (errcode(ERRCODE_CONNECTION_FAILURE),
    2201             :                  errmsg("could not receive list of replicated tables from the publisher: %s",
    2202             :                         res->err)));
    2203             : 
    2204             :     /* Process tables. */
    2205         256 :     slot = MakeSingleTupleTableSlot(res->tupledesc, &TTSOpsMinimalTuple);
    2206         730 :     while (tuplestore_gettupleslot(res->tuplestore, true, false, slot))
    2207             :     {
    2208             :         char       *nspname;
    2209             :         char       *relname;
    2210             :         bool        isnull;
    2211             :         RangeVar   *rv;
    2212             : 
    2213         476 :         nspname = TextDatumGetCString(slot_getattr(slot, 1, &isnull));
    2214             :         Assert(!isnull);
    2215         476 :         relname = TextDatumGetCString(slot_getattr(slot, 2, &isnull));
    2216             :         Assert(!isnull);
    2217             : 
    2218         476 :         rv = makeRangeVar(nspname, relname, -1);
    2219             : 
    2220         476 :         if (check_columnlist && list_member(tablelist, rv))
    2221           2 :             ereport(ERROR,
    2222             :                     errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    2223             :                     errmsg("cannot use different column lists for table \"%s.%s\" in different publications",
    2224             :                            nspname, relname));
    2225             :         else
    2226         474 :             tablelist = lappend(tablelist, rv);
    2227             : 
    2228         474 :         ExecClearTuple(slot);
    2229             :     }
    2230         254 :     ExecDropSingleTupleTableSlot(slot);
    2231             : 
    2232         254 :     walrcv_clear_result(res);
    2233             : 
    2234         254 :     return tablelist;
    2235             : }
    2236             : 
    2237             : /*
    2238             :  * This is to report the connection failure while dropping replication slots.
    2239             :  * Here, we report the WARNING for all tablesync slots so that user can drop
    2240             :  * them manually, if required.
    2241             :  */
    2242             : static void
    2243           0 : ReportSlotConnectionError(List *rstates, Oid subid, char *slotname, char *err)
    2244             : {
    2245             :     ListCell   *lc;
    2246             : 
    2247           0 :     foreach(lc, rstates)
    2248             :     {
    2249           0 :         SubscriptionRelState *rstate = (SubscriptionRelState *) lfirst(lc);
    2250           0 :         Oid         relid = rstate->relid;
    2251             : 
    2252             :         /* Only cleanup resources of tablesync workers */
    2253           0 :         if (!OidIsValid(relid))
    2254           0 :             continue;
    2255             : 
    2256             :         /*
    2257             :          * Caller needs to ensure that relstate doesn't change underneath us.
    2258             :          * See DropSubscription where we get the relstates.
    2259             :          */
    2260           0 :         if (rstate->state != SUBREL_STATE_SYNCDONE)
    2261             :         {
    2262           0 :             char        syncslotname[NAMEDATALEN] = {0};
    2263             : 
    2264           0 :             ReplicationSlotNameForTablesync(subid, relid, syncslotname,
    2265             :                                             sizeof(syncslotname));
    2266           0 :             elog(WARNING, "could not drop tablesync replication slot \"%s\"",
    2267             :                  syncslotname);
    2268             :         }
    2269             :     }
    2270             : 
    2271           0 :     ereport(ERROR,
    2272             :             (errcode(ERRCODE_CONNECTION_FAILURE),
    2273             :              errmsg("could not connect to publisher when attempting to drop replication slot \"%s\": %s",
    2274             :                     slotname, err),
    2275             :     /* translator: %s is an SQL ALTER command */
    2276             :              errhint("Use %s to disable the subscription, and then use %s to disassociate it from the slot.",
    2277             :                      "ALTER SUBSCRIPTION ... DISABLE",
    2278             :                      "ALTER SUBSCRIPTION ... SET (slot_name = NONE)")));
    2279             : }
    2280             : 
    2281             : /*
    2282             :  * Check for duplicates in the given list of publications and error out if
    2283             :  * found one.  Add publications to datums as text datums, if datums is not
    2284             :  * NULL.
    2285             :  */
    2286             : static void
    2287         390 : check_duplicates_in_publist(List *publist, Datum *datums)
    2288             : {
    2289             :     ListCell   *cell;
    2290         390 :     int         j = 0;
    2291             : 
    2292         902 :     foreach(cell, publist)
    2293             :     {
    2294         530 :         char       *name = strVal(lfirst(cell));
    2295             :         ListCell   *pcell;
    2296             : 
    2297         802 :         foreach(pcell, publist)
    2298             :         {
    2299         802 :             char       *pname = strVal(lfirst(pcell));
    2300             : 
    2301         802 :             if (pcell == cell)
    2302         512 :                 break;
    2303             : 
    2304         290 :             if (strcmp(name, pname) == 0)
    2305          18 :                 ereport(ERROR,
    2306             :                         (errcode(ERRCODE_DUPLICATE_OBJECT),
    2307             :                          errmsg("publication name \"%s\" used more than once",
    2308             :                                 pname)));
    2309             :         }
    2310             : 
    2311         512 :         if (datums)
    2312         426 :             datums[j++] = CStringGetTextDatum(name);
    2313             :     }
    2314         372 : }
    2315             : 
    2316             : /*
    2317             :  * Merge current subscription's publications and user-specified publications
    2318             :  * from ADD/DROP PUBLICATIONS.
    2319             :  *
    2320             :  * If addpub is true, we will add the list of publications into oldpublist.
    2321             :  * Otherwise, we will delete the list of publications from oldpublist.  The
    2322             :  * returned list is a copy, oldpublist itself is not changed.
    2323             :  *
    2324             :  * subname is the subscription name, for error messages.
    2325             :  */
    2326             : static List *
    2327          54 : merge_publications(List *oldpublist, List *newpublist, bool addpub, const char *subname)
    2328             : {
    2329             :     ListCell   *lc;
    2330             : 
    2331          54 :     oldpublist = list_copy(oldpublist);
    2332             : 
    2333          54 :     check_duplicates_in_publist(newpublist, NULL);
    2334             : 
    2335          92 :     foreach(lc, newpublist)
    2336             :     {
    2337          68 :         char       *name = strVal(lfirst(lc));
    2338             :         ListCell   *lc2;
    2339          68 :         bool        found = false;
    2340             : 
    2341         134 :         foreach(lc2, oldpublist)
    2342             :         {
    2343         110 :             char       *pubname = strVal(lfirst(lc2));
    2344             : 
    2345         110 :             if (strcmp(name, pubname) == 0)
    2346             :             {
    2347          44 :                 found = true;
    2348          44 :                 if (addpub)
    2349          12 :                     ereport(ERROR,
    2350             :                             (errcode(ERRCODE_DUPLICATE_OBJECT),
    2351             :                              errmsg("publication \"%s\" is already in subscription \"%s\"",
    2352             :                                     name, subname)));
    2353             :                 else
    2354          32 :                     oldpublist = foreach_delete_current(oldpublist, lc2);
    2355             : 
    2356          32 :                 break;
    2357             :             }
    2358             :         }
    2359             : 
    2360          56 :         if (addpub && !found)
    2361          18 :             oldpublist = lappend(oldpublist, makeString(name));
    2362          38 :         else if (!addpub && !found)
    2363           6 :             ereport(ERROR,
    2364             :                     (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    2365             :                      errmsg("publication \"%s\" is not in subscription \"%s\"",
    2366             :                             name, subname)));
    2367             :     }
    2368             : 
    2369             :     /*
    2370             :      * XXX Probably no strong reason for this, but for now it's to make ALTER
    2371             :      * SUBSCRIPTION ... DROP PUBLICATION consistent with SET PUBLICATION.
    2372             :      */
    2373          24 :     if (!oldpublist)
    2374           6 :         ereport(ERROR,
    2375             :                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    2376             :                  errmsg("cannot drop all the publications from a subscription")));
    2377             : 
    2378          18 :     return oldpublist;
    2379             : }
    2380             : 
    2381             : /*
    2382             :  * Extract the streaming mode value from a DefElem.  This is like
    2383             :  * defGetBoolean() but also accepts the special value of "parallel".
    2384             :  */
    2385             : char
    2386         132 : defGetStreamingMode(DefElem *def)
    2387             : {
    2388             :     /*
    2389             :      * If no parameter value given, assume "true" is meant.
    2390             :      */
    2391         132 :     if (!def->arg)
    2392           0 :         return LOGICALREP_STREAM_ON;
    2393             : 
    2394             :     /*
    2395             :      * Allow 0, 1, "false", "true", "off", "on" or "parallel".
    2396             :      */
    2397         132 :     switch (nodeTag(def->arg))
    2398             :     {
    2399           0 :         case T_Integer:
    2400           0 :             switch (intVal(def->arg))
    2401             :             {
    2402           0 :                 case 0:
    2403           0 :                     return LOGICALREP_STREAM_OFF;
    2404           0 :                 case 1:
    2405           0 :                     return LOGICALREP_STREAM_ON;
    2406           0 :                 default:
    2407             :                     /* otherwise, error out below */
    2408           0 :                     break;
    2409             :             }
    2410           0 :             break;
    2411         132 :         default:
    2412             :             {
    2413         132 :                 char       *sval = defGetString(def);
    2414             : 
    2415             :                 /*
    2416             :                  * The set of strings accepted here should match up with the
    2417             :                  * grammar's opt_boolean_or_string production.
    2418             :                  */
    2419         258 :                 if (pg_strcasecmp(sval, "false") == 0 ||
    2420         126 :                     pg_strcasecmp(sval, "off") == 0)
    2421           6 :                     return LOGICALREP_STREAM_OFF;
    2422         234 :                 if (pg_strcasecmp(sval, "true") == 0 ||
    2423         108 :                     pg_strcasecmp(sval, "on") == 0)
    2424          90 :                     return LOGICALREP_STREAM_ON;
    2425          36 :                 if (pg_strcasecmp(sval, "parallel") == 0)
    2426          30 :                     return LOGICALREP_STREAM_PARALLEL;
    2427             :             }
    2428           6 :             break;
    2429             :     }
    2430             : 
    2431           6 :     ereport(ERROR,
    2432             :             (errcode(ERRCODE_SYNTAX_ERROR),
    2433             :              errmsg("%s requires a Boolean value or \"parallel\"",
    2434             :                     def->defname)));
    2435             :     return LOGICALREP_STREAM_OFF;   /* keep compiler quiet */
    2436             : }

Generated by: LCOV version 1.14