LCOV - code coverage report
Current view: top level - src/backend/commands - subscriptioncmds.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 90.1 % 1238 1116
Test Date: 2026-08-15 10:15:37 Functions: 100.0 % 27 27
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 72.7 % 1042 758

             Branch data     Line data    Source code
       1                 :             : /*-------------------------------------------------------------------------
       2                 :             :  *
       3                 :             :  * subscriptioncmds.c
       4                 :             :  *      subscription catalog manipulation functions
       5                 :             :  *
       6                 :             :  * Portions Copyright (c) 1996-2026, 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/commit_ts.h"
      18                 :             : #include "access/htup_details.h"
      19                 :             : #include "access/table.h"
      20                 :             : #include "access/twophase.h"
      21                 :             : #include "access/xact.h"
      22                 :             : #include "catalog/catalog.h"
      23                 :             : #include "catalog/dependency.h"
      24                 :             : #include "catalog/indexing.h"
      25                 :             : #include "catalog/namespace.h"
      26                 :             : #include "catalog/objectaccess.h"
      27                 :             : #include "catalog/objectaddress.h"
      28                 :             : #include "catalog/pg_authid_d.h"
      29                 :             : #include "catalog/pg_database_d.h"
      30                 :             : #include "catalog/pg_foreign_server.h"
      31                 :             : #include "catalog/pg_namespace.h"
      32                 :             : #include "catalog/pg_subscription.h"
      33                 :             : #include "catalog/pg_subscription_rel.h"
      34                 :             : #include "catalog/pg_type.h"
      35                 :             : #include "catalog/pg_user_mapping.h"
      36                 :             : #include "commands/defrem.h"
      37                 :             : #include "commands/event_trigger.h"
      38                 :             : #include "commands/subscriptioncmds.h"
      39                 :             : #include "commands/tablecmds.h"
      40                 :             : #include "executor/executor.h"
      41                 :             : #include "foreign/foreign.h"
      42                 :             : #include "miscadmin.h"
      43                 :             : #include "nodes/makefuncs.h"
      44                 :             : #include "pgstat.h"
      45                 :             : #include "replication/logicallauncher.h"
      46                 :             : #include "replication/logicalworker.h"
      47                 :             : #include "replication/origin.h"
      48                 :             : #include "replication/slot.h"
      49                 :             : #include "replication/walreceiver.h"
      50                 :             : #include "replication/walsender.h"
      51                 :             : #include "replication/worker_internal.h"
      52                 :             : #include "storage/lmgr.h"
      53                 :             : #include "storage/lock.h"
      54                 :             : #include "utils/acl.h"
      55                 :             : #include "utils/builtins.h"
      56                 :             : #include "utils/guc.h"
      57                 :             : #include "utils/lsyscache.h"
      58                 :             : #include "utils/memutils.h"
      59                 :             : #include "utils/pg_lsn.h"
      60                 :             : #include "utils/syscache.h"
      61                 :             : 
      62                 :             : /*
      63                 :             :  * Options that can be specified by the user in CREATE/ALTER SUBSCRIPTION
      64                 :             :  * command.
      65                 :             :  */
      66                 :             : #define SUBOPT_CONNECT              0x00000001
      67                 :             : #define SUBOPT_ENABLED              0x00000002
      68                 :             : #define SUBOPT_CREATE_SLOT          0x00000004
      69                 :             : #define SUBOPT_SLOT_NAME            0x00000008
      70                 :             : #define SUBOPT_COPY_DATA            0x00000010
      71                 :             : #define SUBOPT_SYNCHRONOUS_COMMIT   0x00000020
      72                 :             : #define SUBOPT_REFRESH              0x00000040
      73                 :             : #define SUBOPT_BINARY               0x00000080
      74                 :             : #define SUBOPT_STREAMING            0x00000100
      75                 :             : #define SUBOPT_TWOPHASE_COMMIT      0x00000200
      76                 :             : #define SUBOPT_DISABLE_ON_ERR       0x00000400
      77                 :             : #define SUBOPT_PASSWORD_REQUIRED    0x00000800
      78                 :             : #define SUBOPT_RUN_AS_OWNER         0x00001000
      79                 :             : #define SUBOPT_FAILOVER             0x00002000
      80                 :             : #define SUBOPT_RETAIN_DEAD_TUPLES   0x00004000
      81                 :             : #define SUBOPT_MAX_RETENTION_DURATION   0x00008000
      82                 :             : #define SUBOPT_WAL_RECEIVER_TIMEOUT         0x00010000
      83                 :             : #define SUBOPT_LSN                  0x00020000
      84                 :             : #define SUBOPT_ORIGIN               0x00040000
      85                 :             : #define SUBOPT_CONFLICT_LOG_DEST    0x00080000
      86                 :             : 
      87                 :             : /* check if the 'val' has 'bits' set */
      88                 :             : #define IsSet(val, bits)  (((val) & (bits)) == (bits))
      89                 :             : 
      90                 :             : /*
      91                 :             :  * Structure to hold a bitmap representing the user-provided CREATE/ALTER
      92                 :             :  * SUBSCRIPTION command options and the parsed/default values of each of them.
      93                 :             :  */
      94                 :             : typedef struct SubOpts
      95                 :             : {
      96                 :             :     uint32      specified_opts;
      97                 :             :     char       *slot_name;
      98                 :             :     char       *synchronous_commit;
      99                 :             :     bool        connect;
     100                 :             :     bool        enabled;
     101                 :             :     bool        create_slot;
     102                 :             :     bool        copy_data;
     103                 :             :     bool        refresh;
     104                 :             :     bool        binary;
     105                 :             :     char        streaming;
     106                 :             :     bool        twophase;
     107                 :             :     bool        disableonerr;
     108                 :             :     bool        passwordrequired;
     109                 :             :     bool        runasowner;
     110                 :             :     bool        failover;
     111                 :             :     bool        retaindeadtuples;
     112                 :             :     int32       maxretention;
     113                 :             :     char       *origin;
     114                 :             :     ConflictLogDest conflictlogdest;
     115                 :             :     XLogRecPtr  lsn;
     116                 :             :     char       *wal_receiver_timeout;
     117                 :             : } SubOpts;
     118                 :             : 
     119                 :             : /*
     120                 :             :  * PublicationRelKind represents a relation included in a publication.
     121                 :             :  * It stores the schema-qualified relation name (rv) and its kind (relkind).
     122                 :             :  */
     123                 :             : typedef struct PublicationRelKind
     124                 :             : {
     125                 :             :     RangeVar   *rv;
     126                 :             :     char        relkind;
     127                 :             : } PublicationRelKind;
     128                 :             : 
     129                 :             : static List *fetch_relation_list(WalReceiverConn *wrconn, List *publications);
     130                 :             : static void check_publications_origin_tables(WalReceiverConn *wrconn,
     131                 :             :                                              List *publications, bool copydata,
     132                 :             :                                              bool retain_dead_tuples,
     133                 :             :                                              char *origin,
     134                 :             :                                              Oid *subrel_local_oids,
     135                 :             :                                              int subrel_count, char *subname);
     136                 :             : static void check_publications_origin_sequences(WalReceiverConn *wrconn,
     137                 :             :                                                 List *publications,
     138                 :             :                                                 bool copydata, char *origin,
     139                 :             :                                                 Oid *subrel_local_oids,
     140                 :             :                                                 int subrel_count,
     141                 :             :                                                 char *subname);
     142                 :             : static void check_duplicates_in_publist(List *publist, Datum *datums);
     143                 :             : static List *merge_publications(List *oldpublist, List *newpublist, bool addpub, const char *subname);
     144                 :             : static void ReportSlotConnectionError(List *rstates, Oid subid, char *slotname, char *err);
     145                 :             : static void CheckAlterSubOption(Subscription *sub, const char *option,
     146                 :             :                                 bool slot_needs_update, bool isTopLevel);
     147                 :             : static bool alter_sub_conflict_log_dest(Subscription *sub,
     148                 :             :                                         ConflictLogDest oldlogdest,
     149                 :             :                                         ConflictLogDest newlogdest,
     150                 :             :                                         Oid *conflicttablerelid);
     151                 :             : static void drop_sub_conflict_log_table(Oid subid, char *subname,
     152                 :             :                                         Oid subconflictlogrelid);
     153                 :             : 
     154                 :             : /*
     155                 :             :  * Common option parsing function for CREATE and ALTER SUBSCRIPTION commands.
     156                 :             :  *
     157                 :             :  * Since not all options can be specified in both commands, this function
     158                 :             :  * will report an error if mutually exclusive options are specified.
     159                 :             :  */
     160                 :             : static void
     161                 :         745 : parse_subscription_options(ParseState *pstate, List *stmt_options,
     162                 :             :                            uint32 supported_opts, SubOpts *opts)
     163                 :             : {
     164                 :             :     ListCell   *lc;
     165                 :             : 
     166                 :             :     /* Start out with cleared opts. */
     167                 :         745 :     memset(opts, 0, sizeof(SubOpts));
     168                 :             : 
     169                 :             :     /* caller must expect some option */
     170                 :             :     Assert(supported_opts != 0);
     171                 :             : 
     172                 :             :     /* If connect option is supported, these others also need to be. */
     173                 :             :     Assert(!IsSet(supported_opts, SUBOPT_CONNECT) ||
     174                 :             :            IsSet(supported_opts, SUBOPT_ENABLED | SUBOPT_CREATE_SLOT |
     175                 :             :                  SUBOPT_COPY_DATA));
     176                 :             : 
     177                 :             :     /* Set default values for the supported options. */
     178         [ +  + ]:         745 :     if (IsSet(supported_opts, SUBOPT_CONNECT))
     179                 :         335 :         opts->connect = true;
     180         [ +  + ]:         745 :     if (IsSet(supported_opts, SUBOPT_ENABLED))
     181                 :         422 :         opts->enabled = true;
     182         [ +  + ]:         745 :     if (IsSet(supported_opts, SUBOPT_CREATE_SLOT))
     183                 :         335 :         opts->create_slot = true;
     184         [ +  + ]:         745 :     if (IsSet(supported_opts, SUBOPT_COPY_DATA))
     185                 :         434 :         opts->copy_data = true;
     186         [ +  + ]:         745 :     if (IsSet(supported_opts, SUBOPT_REFRESH))
     187                 :          58 :         opts->refresh = true;
     188         [ +  + ]:         745 :     if (IsSet(supported_opts, SUBOPT_BINARY))
     189                 :         544 :         opts->binary = false;
     190         [ +  + ]:         745 :     if (IsSet(supported_opts, SUBOPT_STREAMING))
     191                 :         544 :         opts->streaming = LOGICALREP_STREAM_PARALLEL;
     192         [ +  + ]:         745 :     if (IsSet(supported_opts, SUBOPT_TWOPHASE_COMMIT))
     193                 :         544 :         opts->twophase = false;
     194         [ +  + ]:         745 :     if (IsSet(supported_opts, SUBOPT_DISABLE_ON_ERR))
     195                 :         544 :         opts->disableonerr = false;
     196         [ +  + ]:         745 :     if (IsSet(supported_opts, SUBOPT_PASSWORD_REQUIRED))
     197                 :         544 :         opts->passwordrequired = true;
     198         [ +  + ]:         745 :     if (IsSet(supported_opts, SUBOPT_RUN_AS_OWNER))
     199                 :         544 :         opts->runasowner = false;
     200         [ +  + ]:         745 :     if (IsSet(supported_opts, SUBOPT_FAILOVER))
     201                 :         544 :         opts->failover = false;
     202         [ +  + ]:         745 :     if (IsSet(supported_opts, SUBOPT_RETAIN_DEAD_TUPLES))
     203                 :         544 :         opts->retaindeadtuples = false;
     204         [ +  + ]:         745 :     if (IsSet(supported_opts, SUBOPT_MAX_RETENTION_DURATION))
     205                 :         544 :         opts->maxretention = 0;
     206         [ +  + ]:         745 :     if (IsSet(supported_opts, SUBOPT_ORIGIN))
     207                 :         544 :         opts->origin = pstrdup(LOGICALREP_ORIGIN_ANY);
     208         [ +  + ]:         745 :     if (IsSet(supported_opts, SUBOPT_CONFLICT_LOG_DEST))
     209                 :         544 :         opts->conflictlogdest = CONFLICT_LOG_DEST_LOG;
     210                 :             : 
     211                 :             :     /* Parse options */
     212   [ +  +  +  +  :        1506 :     foreach(lc, stmt_options)
                   +  + ]
     213                 :             :     {
     214                 :         825 :         DefElem    *defel = (DefElem *) lfirst(lc);
     215                 :             : 
     216         [ +  + ]:         825 :         if (IsSet(supported_opts, SUBOPT_CONNECT) &&
     217         [ +  + ]:         459 :             strcmp(defel->defname, "connect") == 0)
     218                 :             :         {
     219         [ -  + ]:         171 :             if (IsSet(opts->specified_opts, SUBOPT_CONNECT))
     220                 :           0 :                 errorConflictingDefElem(defel, pstate);
     221                 :             : 
     222                 :         171 :             opts->specified_opts |= SUBOPT_CONNECT;
     223                 :         171 :             opts->connect = defGetBoolean(defel);
     224                 :             :         }
     225         [ +  + ]:         654 :         else if (IsSet(supported_opts, SUBOPT_ENABLED) &&
     226         [ +  + ]:         375 :                  strcmp(defel->defname, "enabled") == 0)
     227                 :             :         {
     228         [ -  + ]:         111 :             if (IsSet(opts->specified_opts, SUBOPT_ENABLED))
     229                 :           0 :                 errorConflictingDefElem(defel, pstate);
     230                 :             : 
     231                 :         111 :             opts->specified_opts |= SUBOPT_ENABLED;
     232                 :         111 :             opts->enabled = defGetBoolean(defel);
     233                 :             :         }
     234         [ +  + ]:         543 :         else if (IsSet(supported_opts, SUBOPT_CREATE_SLOT) &&
     235         [ +  + ]:         264 :                  strcmp(defel->defname, "create_slot") == 0)
     236                 :             :         {
     237         [ -  + ]:          25 :             if (IsSet(opts->specified_opts, SUBOPT_CREATE_SLOT))
     238                 :           0 :                 errorConflictingDefElem(defel, pstate);
     239                 :             : 
     240                 :          25 :             opts->specified_opts |= SUBOPT_CREATE_SLOT;
     241                 :          25 :             opts->create_slot = defGetBoolean(defel);
     242                 :             :         }
     243         [ +  + ]:         518 :         else if (IsSet(supported_opts, SUBOPT_SLOT_NAME) &&
     244         [ +  + ]:         450 :                  strcmp(defel->defname, "slot_name") == 0)
     245                 :             :         {
     246         [ -  + ]:         143 :             if (IsSet(opts->specified_opts, SUBOPT_SLOT_NAME))
     247                 :           0 :                 errorConflictingDefElem(defel, pstate);
     248                 :             : 
     249                 :         143 :             opts->specified_opts |= SUBOPT_SLOT_NAME;
     250                 :         143 :             opts->slot_name = defGetString(defel);
     251                 :             : 
     252                 :             :             /* Setting slot_name = NONE is treated as no slot name. */
     253         [ +  + ]:         282 :             if (strcmp(opts->slot_name, "none") == 0)
     254                 :         115 :                 opts->slot_name = NULL;
     255                 :             :             else
     256                 :          28 :                 ReplicationSlotValidateName(opts->slot_name, false, ERROR);
     257                 :             :         }
     258         [ +  + ]:         375 :         else if (IsSet(supported_opts, SUBOPT_COPY_DATA) &&
     259         [ +  + ]:         225 :                  strcmp(defel->defname, "copy_data") == 0)
     260                 :             :         {
     261         [ -  + ]:          31 :             if (IsSet(opts->specified_opts, SUBOPT_COPY_DATA))
     262                 :           0 :                 errorConflictingDefElem(defel, pstate);
     263                 :             : 
     264                 :          31 :             opts->specified_opts |= SUBOPT_COPY_DATA;
     265                 :          31 :             opts->copy_data = defGetBoolean(defel);
     266                 :             :         }
     267         [ +  + ]:         344 :         else if (IsSet(supported_opts, SUBOPT_SYNCHRONOUS_COMMIT) &&
     268         [ +  + ]:         281 :                  strcmp(defel->defname, "synchronous_commit") == 0)
     269                 :             :         {
     270         [ -  + ]:          16 :             if (IsSet(opts->specified_opts, SUBOPT_SYNCHRONOUS_COMMIT))
     271                 :           0 :                 errorConflictingDefElem(defel, pstate);
     272                 :             : 
     273                 :          16 :             opts->specified_opts |= SUBOPT_SYNCHRONOUS_COMMIT;
     274                 :          16 :             opts->synchronous_commit = defGetString(defel);
     275                 :             : 
     276                 :             :             /* Test if the given value is valid for synchronous_commit GUC. */
     277                 :          16 :             (void) set_config_option("synchronous_commit", opts->synchronous_commit,
     278                 :             :                                      PGC_BACKEND, PGC_S_TEST, GUC_ACTION_SET,
     279                 :             :                                      false, 0, false);
     280                 :             :         }
     281         [ +  + ]:         328 :         else if (IsSet(supported_opts, SUBOPT_REFRESH) &&
     282         [ +  - ]:          48 :                  strcmp(defel->defname, "refresh") == 0)
     283                 :             :         {
     284         [ -  + ]:          48 :             if (IsSet(opts->specified_opts, SUBOPT_REFRESH))
     285                 :           0 :                 errorConflictingDefElem(defel, pstate);
     286                 :             : 
     287                 :          48 :             opts->specified_opts |= SUBOPT_REFRESH;
     288                 :          48 :             opts->refresh = defGetBoolean(defel);
     289                 :             :         }
     290         [ +  + ]:         280 :         else if (IsSet(supported_opts, SUBOPT_BINARY) &&
     291         [ +  + ]:         265 :                  strcmp(defel->defname, "binary") == 0)
     292                 :             :         {
     293         [ -  + ]:          19 :             if (IsSet(opts->specified_opts, SUBOPT_BINARY))
     294                 :           0 :                 errorConflictingDefElem(defel, pstate);
     295                 :             : 
     296                 :          19 :             opts->specified_opts |= SUBOPT_BINARY;
     297                 :          19 :             opts->binary = defGetBoolean(defel);
     298                 :             :         }
     299         [ +  + ]:         261 :         else if (IsSet(supported_opts, SUBOPT_STREAMING) &&
     300         [ +  + ]:         246 :                  strcmp(defel->defname, "streaming") == 0)
     301                 :             :         {
     302         [ -  + ]:          43 :             if (IsSet(opts->specified_opts, SUBOPT_STREAMING))
     303                 :           0 :                 errorConflictingDefElem(defel, pstate);
     304                 :             : 
     305                 :          43 :             opts->specified_opts |= SUBOPT_STREAMING;
     306                 :          43 :             opts->streaming = defGetStreamingMode(defel);
     307                 :             :         }
     308         [ +  + ]:         218 :         else if (IsSet(supported_opts, SUBOPT_TWOPHASE_COMMIT) &&
     309         [ +  + ]:         203 :                  strcmp(defel->defname, "two_phase") == 0)
     310                 :             :         {
     311         [ -  + ]:          24 :             if (IsSet(opts->specified_opts, SUBOPT_TWOPHASE_COMMIT))
     312                 :           0 :                 errorConflictingDefElem(defel, pstate);
     313                 :             : 
     314                 :          24 :             opts->specified_opts |= SUBOPT_TWOPHASE_COMMIT;
     315                 :          24 :             opts->twophase = defGetBoolean(defel);
     316                 :             :         }
     317         [ +  + ]:         194 :         else if (IsSet(supported_opts, SUBOPT_DISABLE_ON_ERR) &&
     318         [ +  + ]:         179 :                  strcmp(defel->defname, "disable_on_error") == 0)
     319                 :             :         {
     320         [ -  + ]:          21 :             if (IsSet(opts->specified_opts, SUBOPT_DISABLE_ON_ERR))
     321                 :           0 :                 errorConflictingDefElem(defel, pstate);
     322                 :             : 
     323                 :          21 :             opts->specified_opts |= SUBOPT_DISABLE_ON_ERR;
     324                 :          21 :             opts->disableonerr = defGetBoolean(defel);
     325                 :             :         }
     326         [ +  + ]:         173 :         else if (IsSet(supported_opts, SUBOPT_PASSWORD_REQUIRED) &&
     327         [ +  + ]:         158 :                  strcmp(defel->defname, "password_required") == 0)
     328                 :             :         {
     329         [ -  + ]:          17 :             if (IsSet(opts->specified_opts, SUBOPT_PASSWORD_REQUIRED))
     330                 :           0 :                 errorConflictingDefElem(defel, pstate);
     331                 :             : 
     332                 :          17 :             opts->specified_opts |= SUBOPT_PASSWORD_REQUIRED;
     333                 :          17 :             opts->passwordrequired = defGetBoolean(defel);
     334                 :             :         }
     335         [ +  + ]:         156 :         else if (IsSet(supported_opts, SUBOPT_RUN_AS_OWNER) &&
     336         [ +  + ]:         141 :                  strcmp(defel->defname, "run_as_owner") == 0)
     337                 :             :         {
     338         [ -  + ]:          11 :             if (IsSet(opts->specified_opts, SUBOPT_RUN_AS_OWNER))
     339                 :           0 :                 errorConflictingDefElem(defel, pstate);
     340                 :             : 
     341                 :          11 :             opts->specified_opts |= SUBOPT_RUN_AS_OWNER;
     342                 :          11 :             opts->runasowner = defGetBoolean(defel);
     343                 :             :         }
     344         [ +  + ]:         145 :         else if (IsSet(supported_opts, SUBOPT_FAILOVER) &&
     345         [ +  + ]:         130 :                  strcmp(defel->defname, "failover") == 0)
     346                 :             :         {
     347         [ -  + ]:          16 :             if (IsSet(opts->specified_opts, SUBOPT_FAILOVER))
     348                 :           0 :                 errorConflictingDefElem(defel, pstate);
     349                 :             : 
     350                 :          16 :             opts->specified_opts |= SUBOPT_FAILOVER;
     351                 :          16 :             opts->failover = defGetBoolean(defel);
     352                 :             :         }
     353         [ +  + ]:         129 :         else if (IsSet(supported_opts, SUBOPT_RETAIN_DEAD_TUPLES) &&
     354         [ +  + ]:         114 :                  strcmp(defel->defname, "retain_dead_tuples") == 0)
     355                 :             :         {
     356         [ -  + ]:          14 :             if (IsSet(opts->specified_opts, SUBOPT_RETAIN_DEAD_TUPLES))
     357                 :           0 :                 errorConflictingDefElem(defel, pstate);
     358                 :             : 
     359                 :          14 :             opts->specified_opts |= SUBOPT_RETAIN_DEAD_TUPLES;
     360                 :          14 :             opts->retaindeadtuples = defGetBoolean(defel);
     361                 :             :         }
     362         [ +  + ]:         115 :         else if (IsSet(supported_opts, SUBOPT_MAX_RETENTION_DURATION) &&
     363         [ +  + ]:         100 :                  strcmp(defel->defname, "max_retention_duration") == 0)
     364                 :             :         {
     365         [ -  + ]:          22 :             if (IsSet(opts->specified_opts, SUBOPT_MAX_RETENTION_DURATION))
     366                 :           0 :                 errorConflictingDefElem(defel, pstate);
     367                 :             : 
     368                 :          22 :             opts->specified_opts |= SUBOPT_MAX_RETENTION_DURATION;
     369                 :          22 :             opts->maxretention = defGetInt32(defel);
     370                 :             : 
     371         [ +  + ]:          18 :             if (opts->maxretention < 0)
     372         [ +  - ]:           8 :                 ereport(ERROR,
     373                 :             :                         errcode(ERRCODE_INVALID_PARAMETER_VALUE),
     374                 :             :                         errmsg("max_retention_duration cannot be negative"));
     375                 :             :         }
     376         [ +  + ]:          93 :         else if (IsSet(supported_opts, SUBOPT_ORIGIN) &&
     377         [ +  + ]:          78 :                  strcmp(defel->defname, "origin") == 0)
     378                 :             :         {
     379         [ -  + ]:          24 :             if (IsSet(opts->specified_opts, SUBOPT_ORIGIN))
     380                 :           0 :                 errorConflictingDefElem(defel, pstate);
     381                 :             : 
     382                 :          24 :             opts->specified_opts |= SUBOPT_ORIGIN;
     383                 :          24 :             pfree(opts->origin);
     384                 :             : 
     385                 :             :             /*
     386                 :             :              * Even though the "origin" parameter allows only "none" and "any"
     387                 :             :              * values, it is implemented as a string type so that the
     388                 :             :              * parameter can be extended in future versions to support
     389                 :             :              * filtering using origin names specified by the user.
     390                 :             :              */
     391                 :          24 :             opts->origin = defGetString(defel);
     392                 :             : 
     393   [ +  +  +  + ]:          34 :             if ((pg_strcasecmp(opts->origin, LOGICALREP_ORIGIN_NONE) != 0) &&
     394                 :          10 :                 (pg_strcasecmp(opts->origin, LOGICALREP_ORIGIN_ANY) != 0))
     395         [ +  - ]:           4 :                 ereport(ERROR,
     396                 :             :                         errcode(ERRCODE_INVALID_PARAMETER_VALUE),
     397                 :             :                         errmsg("unrecognized origin value: \"%s\"", opts->origin));
     398                 :             :         }
     399         [ +  + ]:          69 :         else if (IsSet(supported_opts, SUBOPT_LSN) &&
     400         [ +  - ]:          15 :                  strcmp(defel->defname, "lsn") == 0)
     401                 :          11 :         {
     402                 :          15 :             char       *lsn_str = defGetString(defel);
     403                 :             :             XLogRecPtr  lsn;
     404                 :             : 
     405         [ -  + ]:          15 :             if (IsSet(opts->specified_opts, SUBOPT_LSN))
     406                 :           0 :                 errorConflictingDefElem(defel, pstate);
     407                 :             : 
     408                 :             :             /* Setting lsn = NONE is treated as resetting LSN */
     409         [ +  + ]:          15 :             if (strcmp(lsn_str, "none") == 0)
     410                 :           4 :                 lsn = InvalidXLogRecPtr;
     411                 :             :             else
     412                 :             :             {
     413                 :             :                 /* Parse the argument as LSN */
     414                 :          11 :                 lsn = DatumGetLSN(DirectFunctionCall1(pg_lsn_in,
     415                 :             :                                                       CStringGetDatum(lsn_str)));
     416                 :             : 
     417         [ +  + ]:          11 :                 if (!XLogRecPtrIsValid(lsn))
     418         [ +  - ]:           4 :                     ereport(ERROR,
     419                 :             :                             (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
     420                 :             :                              errmsg("invalid WAL location (LSN): %s", lsn_str)));
     421                 :             :             }
     422                 :             : 
     423                 :          11 :             opts->specified_opts |= SUBOPT_LSN;
     424                 :          11 :             opts->lsn = lsn;
     425                 :             :         }
     426         [ +  - ]:          54 :         else if (IsSet(supported_opts, SUBOPT_WAL_RECEIVER_TIMEOUT) &&
     427         [ +  + ]:          54 :                  strcmp(defel->defname, "wal_receiver_timeout") == 0)
     428                 :           8 :         {
     429                 :             :             bool        parsed;
     430                 :             :             int         val;
     431                 :             : 
     432         [ -  + ]:          12 :             if (IsSet(opts->specified_opts, SUBOPT_WAL_RECEIVER_TIMEOUT))
     433                 :           0 :                 errorConflictingDefElem(defel, pstate);
     434                 :             : 
     435                 :          12 :             opts->specified_opts |= SUBOPT_WAL_RECEIVER_TIMEOUT;
     436                 :          12 :             opts->wal_receiver_timeout = defGetString(defel);
     437                 :             : 
     438                 :             :             /*
     439                 :             :              * Test if the given value is valid for wal_receiver_timeout GUC.
     440                 :             :              * Skip this test if the value is -1, since -1 is allowed for the
     441                 :             :              * wal_receiver_timeout subscription option, but not for the GUC
     442                 :             :              * itself.
     443                 :             :              */
     444                 :          12 :             parsed = parse_int(opts->wal_receiver_timeout, &val, 0, NULL);
     445   [ +  +  -  + ]:          12 :             if (!parsed || val != -1)
     446                 :           8 :                 (void) set_config_option("wal_receiver_timeout", opts->wal_receiver_timeout,
     447                 :             :                                          PGC_BACKEND, PGC_S_TEST, GUC_ACTION_SET,
     448                 :             :                                          false, 0, false);
     449                 :             :         }
     450         [ +  - ]:          42 :         else if (IsSet(supported_opts, SUBOPT_CONFLICT_LOG_DEST) &&
     451         [ +  + ]:          42 :                  strcmp(defel->defname, "conflict_log_destination") == 0)
     452                 :          30 :         {
     453                 :             :             char       *val;
     454                 :             : 
     455         [ -  + ]:          38 :             if (IsSet(opts->specified_opts, SUBOPT_CONFLICT_LOG_DEST))
     456                 :           0 :                 errorConflictingDefElem(defel, pstate);
     457                 :             : 
     458                 :          38 :             val = defGetString(defel);
     459                 :          38 :             opts->conflictlogdest = GetConflictLogDest(val);
     460                 :          30 :             opts->specified_opts |= SUBOPT_CONFLICT_LOG_DEST;
     461                 :             :         }
     462                 :             :         else
     463         [ +  - ]:           4 :             ereport(ERROR,
     464                 :             :                     (errcode(ERRCODE_SYNTAX_ERROR),
     465                 :             :                      errmsg("unrecognized subscription parameter: \"%s\"", defel->defname)));
     466                 :             :     }
     467                 :             : 
     468                 :             :     /*
     469                 :             :      * We've been explicitly asked to not connect, that requires some
     470                 :             :      * additional processing.
     471                 :             :      */
     472   [ +  +  +  + ]:         681 :     if (!opts->connect && IsSet(supported_opts, SUBOPT_CONNECT))
     473                 :             :     {
     474                 :             :         /* Check for incompatible options from the user. */
     475         [ +  - ]:         131 :         if (opts->enabled &&
     476         [ +  + ]:         131 :             IsSet(opts->specified_opts, SUBOPT_ENABLED))
     477         [ +  - ]:           4 :             ereport(ERROR,
     478                 :             :                     (errcode(ERRCODE_SYNTAX_ERROR),
     479                 :             :             /*- translator: both %s are strings of the form "option = value" */
     480                 :             :                      errmsg("%s and %s are mutually exclusive options",
     481                 :             :                             "connect = false", "enabled = true")));
     482                 :             : 
     483         [ +  + ]:         127 :         if (opts->create_slot &&
     484         [ +  + ]:         123 :             IsSet(opts->specified_opts, SUBOPT_CREATE_SLOT))
     485         [ +  - ]:           4 :             ereport(ERROR,
     486                 :             :                     (errcode(ERRCODE_SYNTAX_ERROR),
     487                 :             :                      errmsg("%s and %s are mutually exclusive options",
     488                 :             :                             "connect = false", "create_slot = true")));
     489                 :             : 
     490         [ +  + ]:         123 :         if (opts->copy_data &&
     491         [ +  + ]:         119 :             IsSet(opts->specified_opts, SUBOPT_COPY_DATA))
     492         [ +  - ]:           4 :             ereport(ERROR,
     493                 :             :                     (errcode(ERRCODE_SYNTAX_ERROR),
     494                 :             :                      errmsg("%s and %s are mutually exclusive options",
     495                 :             :                             "connect = false", "copy_data = true")));
     496                 :             : 
     497                 :             :         /* Change the defaults of other options. */
     498                 :         119 :         opts->enabled = false;
     499                 :         119 :         opts->create_slot = false;
     500                 :         119 :         opts->copy_data = false;
     501                 :             :     }
     502                 :             : 
     503                 :             :     /*
     504                 :             :      * Do additional checking for disallowed combination when slot_name = NONE
     505                 :             :      * was used.
     506                 :             :      */
     507         [ +  + ]:         669 :     if (!opts->slot_name &&
     508         [ +  + ]:         645 :         IsSet(opts->specified_opts, SUBOPT_SLOT_NAME))
     509                 :             :     {
     510         [ +  + ]:         111 :         if (opts->enabled)
     511                 :             :         {
     512         [ +  + ]:          12 :             if (IsSet(opts->specified_opts, SUBOPT_ENABLED))
     513         [ +  - ]:           4 :                 ereport(ERROR,
     514                 :             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     515                 :             :                 /*- translator: both %s are strings of the form "option = value" */
     516                 :             :                          errmsg("%s and %s are mutually exclusive options",
     517                 :             :                                 "slot_name = NONE", "enabled = true")));
     518                 :             :             else
     519         [ +  - ]:           8 :                 ereport(ERROR,
     520                 :             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     521                 :             :                 /*- translator: both %s are strings of the form "option = value" */
     522                 :             :                          errmsg("subscription with %s must also set %s",
     523                 :             :                                 "slot_name = NONE", "enabled = false")));
     524                 :             :         }
     525                 :             : 
     526         [ +  + ]:          99 :         if (opts->create_slot)
     527                 :             :         {
     528         [ +  + ]:           8 :             if (IsSet(opts->specified_opts, SUBOPT_CREATE_SLOT))
     529         [ +  - ]:           4 :                 ereport(ERROR,
     530                 :             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     531                 :             :                 /*- translator: both %s are strings of the form "option = value" */
     532                 :             :                          errmsg("%s and %s are mutually exclusive options",
     533                 :             :                                 "slot_name = NONE", "create_slot = true")));
     534                 :             :             else
     535         [ +  - ]:           4 :                 ereport(ERROR,
     536                 :             :                         (errcode(ERRCODE_SYNTAX_ERROR),
     537                 :             :                 /*- translator: both %s are strings of the form "option = value" */
     538                 :             :                          errmsg("subscription with %s must also set %s",
     539                 :             :                                 "slot_name = NONE", "create_slot = false")));
     540                 :             :         }
     541                 :             :     }
     542                 :         649 : }
     543                 :             : 
     544                 :             : /*
     545                 :             :  * Append a suitably-quoted identifier or string literal to buf.
     546                 :             :  * "quote" should be either a double-quote or single-quote character.
     547                 :             :  *
     548                 :             :  * Caution: this quoting logic is sufficient for identifiers and literals
     549                 :             :  * in the replication grammar, but not always in regular SQL.  Specifically,
     550                 :             :  * it'd fail for a string literal if standard_conforming_strings is off.
     551                 :             :  */
     552                 :             : static void
     553                 :         291 : appendQuotedString(StringInfo buf, const char *str, char quote)
     554                 :             : {
     555                 :         291 :     appendStringInfoChar(buf, quote);
     556         [ +  + ]:        9272 :     while (*str)
     557                 :             :     {
     558                 :        8981 :         char        c = *str++;
     559                 :             : 
     560         [ -  + ]:        8981 :         if (c == quote)
     561                 :           0 :             appendStringInfoChar(buf, c);
     562                 :        8981 :         appendStringInfoChar(buf, c);
     563                 :             :     }
     564                 :         291 :     appendStringInfoChar(buf, quote);
     565                 :         291 : }
     566                 :             : 
     567                 :             : #define appendQuotedIdentifier(b, s)    appendQuotedString(b, s, '"')
     568                 :             : #define appendQuotedLiteral(b, s)       appendQuotedString(b, s, '\'')
     569                 :             : 
     570                 :             : /*
     571                 :             :  * Check that the specified publications are present on the publisher.
     572                 :             :  */
     573                 :             : static void
     574                 :         135 : check_publications(WalReceiverConn *wrconn, List *publications)
     575                 :             : {
     576                 :             :     WalRcvExecResult *res;
     577                 :             :     StringInfoData cmd;
     578                 :             :     TupleTableSlot *slot;
     579                 :         135 :     List       *publicationsCopy = NIL;
     580                 :         135 :     Oid         tableRow[1] = {TEXTOID};
     581                 :             : 
     582                 :         135 :     initStringInfo(&cmd);
     583                 :         135 :     appendStringInfoString(&cmd, "SELECT t.pubname FROM\n"
     584                 :             :                            " pg_catalog.pg_publication t WHERE\n"
     585                 :             :                            " t.pubname IN (");
     586                 :         135 :     GetPublicationsStr(publications, &cmd, true);
     587                 :         135 :     appendStringInfoChar(&cmd, ')');
     588                 :             : 
     589                 :         135 :     res = walrcv_exec(wrconn, cmd.data, 1, tableRow);
     590                 :         135 :     pfree(cmd.data);
     591                 :             : 
     592         [ -  + ]:         135 :     if (res->status != WALRCV_OK_TUPLES)
     593         [ #  # ]:           0 :         ereport(ERROR,
     594                 :             :                 errmsg("could not receive list of publications from the publisher: %s",
     595                 :             :                        res->err));
     596                 :             : 
     597                 :         135 :     publicationsCopy = list_copy(publications);
     598                 :             : 
     599                 :             :     /* Process publication(s). */
     600                 :         135 :     slot = MakeSingleTupleTableSlot(res->tupledesc, &TTSOpsMinimalTuple);
     601         [ +  + ]:         299 :     while (tuplestore_gettupleslot(res->tuplestore, true, false, slot))
     602                 :             :     {
     603                 :             :         char       *pubname;
     604                 :             :         bool        isnull;
     605                 :             : 
     606                 :         164 :         pubname = TextDatumGetCString(slot_getattr(slot, 1, &isnull));
     607                 :             :         Assert(!isnull);
     608                 :             : 
     609                 :             :         /* Delete the publication present in publisher from the list. */
     610                 :         164 :         publicationsCopy = list_delete(publicationsCopy, makeString(pubname));
     611                 :         164 :         ExecClearTuple(slot);
     612                 :             :     }
     613                 :             : 
     614                 :         135 :     ExecDropSingleTupleTableSlot(slot);
     615                 :             : 
     616                 :         135 :     walrcv_clear_result(res);
     617                 :             : 
     618         [ +  + ]:         135 :     if (list_length(publicationsCopy))
     619                 :             :     {
     620                 :             :         /* Prepare the list of non-existent publication(s) for error message. */
     621                 :             :         StringInfoData pubnames;
     622                 :             : 
     623                 :           4 :         initStringInfo(&pubnames);
     624                 :             : 
     625                 :           4 :         GetPublicationsStr(publicationsCopy, &pubnames, false);
     626         [ +  - ]:           4 :         ereport(WARNING,
     627                 :             :                 errcode(ERRCODE_UNDEFINED_OBJECT),
     628                 :             :                 errmsg_plural("publication %s does not exist on the publisher",
     629                 :             :                               "publications %s do not exist on the publisher",
     630                 :             :                               list_length(publicationsCopy),
     631                 :             :                               pubnames.data));
     632                 :             :     }
     633                 :         135 : }
     634                 :             : 
     635                 :             : /*
     636                 :             :  * Auxiliary function to build a text array out of a list of String nodes.
     637                 :             :  */
     638                 :             : static Datum
     639                 :         255 : publicationListToArray(List *publist)
     640                 :             : {
     641                 :             :     ArrayType  *arr;
     642                 :             :     Datum      *datums;
     643                 :             :     MemoryContext memcxt;
     644                 :             :     MemoryContext oldcxt;
     645                 :             : 
     646                 :             :     /* Create memory context for temporary allocations. */
     647                 :         255 :     memcxt = AllocSetContextCreate(CurrentMemoryContext,
     648                 :             :                                    "publicationListToArray to array",
     649                 :             :                                    ALLOCSET_DEFAULT_SIZES);
     650                 :         255 :     oldcxt = MemoryContextSwitchTo(memcxt);
     651                 :             : 
     652                 :         255 :     datums = palloc_array(Datum, list_length(publist));
     653                 :             : 
     654                 :         255 :     check_duplicates_in_publist(publist, datums);
     655                 :             : 
     656                 :         251 :     MemoryContextSwitchTo(oldcxt);
     657                 :             : 
     658                 :         251 :     arr = construct_array_builtin(datums, list_length(publist), TEXTOID);
     659                 :             : 
     660                 :         251 :     MemoryContextDelete(memcxt);
     661                 :             : 
     662                 :         251 :     return PointerGetDatum(arr);
     663                 :             : }
     664                 :             : 
     665                 :             : /*
     666                 :             :  * Create new subscription.
     667                 :             :  */
     668                 :             : ObjectAddress
     669                 :         335 : CreateSubscription(ParseState *pstate, CreateSubscriptionStmt *stmt,
     670                 :             :                    bool isTopLevel)
     671                 :             : {
     672                 :             :     Relation    rel;
     673                 :             :     ObjectAddress myself;
     674                 :             :     Oid         subid;
     675                 :             :     bool        nulls[Natts_pg_subscription];
     676                 :             :     Datum       values[Natts_pg_subscription];
     677                 :         335 :     Oid         owner = GetUserId();
     678                 :             :     HeapTuple   tup;
     679                 :         335 :     Oid         serverid = InvalidOid;
     680                 :         335 :     char       *conninfo = NULL;
     681                 :             :     char        originname[NAMEDATALEN];
     682                 :             :     List       *publications;
     683                 :             :     uint32      supported_opts;
     684                 :         335 :     SubOpts     opts = {0};
     685                 :             :     AclResult   aclresult;
     686                 :         335 :     Oid         logrelid = InvalidOid;
     687                 :             : 
     688                 :             :     /*
     689                 :             :      * Parse and check options.
     690                 :             :      *
     691                 :             :      * Connection and publication should not be specified here.
     692                 :             :      */
     693                 :         335 :     supported_opts = (SUBOPT_CONNECT | SUBOPT_ENABLED | SUBOPT_CREATE_SLOT |
     694                 :             :                       SUBOPT_SLOT_NAME | SUBOPT_COPY_DATA |
     695                 :             :                       SUBOPT_SYNCHRONOUS_COMMIT | SUBOPT_BINARY |
     696                 :             :                       SUBOPT_STREAMING | SUBOPT_TWOPHASE_COMMIT |
     697                 :             :                       SUBOPT_DISABLE_ON_ERR | SUBOPT_PASSWORD_REQUIRED |
     698                 :             :                       SUBOPT_RUN_AS_OWNER | SUBOPT_FAILOVER |
     699                 :             :                       SUBOPT_RETAIN_DEAD_TUPLES |
     700                 :             :                       SUBOPT_MAX_RETENTION_DURATION |
     701                 :             :                       SUBOPT_WAL_RECEIVER_TIMEOUT | SUBOPT_ORIGIN |
     702                 :             :                       SUBOPT_CONFLICT_LOG_DEST);
     703                 :         335 :     parse_subscription_options(pstate, stmt->options, supported_opts, &opts);
     704                 :             : 
     705                 :             :     /*
     706                 :             :      * Since creating a replication slot is not transactional, rolling back
     707                 :             :      * the transaction leaves the created replication slot.  So we cannot run
     708                 :             :      * CREATE SUBSCRIPTION inside a transaction block if creating a
     709                 :             :      * replication slot.
     710                 :             :      */
     711         [ +  + ]:         263 :     if (opts.create_slot)
     712                 :         139 :         PreventInTransactionBlock(isTopLevel, "CREATE SUBSCRIPTION ... WITH (create_slot = true)");
     713                 :             : 
     714                 :             :     /*
     715                 :             :      * We don't want to allow unprivileged users to be able to trigger
     716                 :             :      * attempts to access arbitrary network destinations, so require the user
     717                 :             :      * to have been specifically authorized to create subscriptions.
     718                 :             :      */
     719         [ +  + ]:         259 :     if (!has_privs_of_role(owner, ROLE_PG_CREATE_SUBSCRIPTION))
     720         [ +  - ]:           4 :         ereport(ERROR,
     721                 :             :                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
     722                 :             :                  errmsg("permission denied to create subscription"),
     723                 :             :                  errdetail("Only roles with privileges of the \"%s\" role may create subscriptions.",
     724                 :             :                            "pg_create_subscription")));
     725                 :             : 
     726                 :             :     /*
     727                 :             :      * Since a subscription is a database object, we also check for CREATE
     728                 :             :      * permission on the database.
     729                 :             :      */
     730                 :         255 :     aclresult = object_aclcheck(DatabaseRelationId, MyDatabaseId,
     731                 :             :                                 owner, ACL_CREATE);
     732         [ +  + ]:         255 :     if (aclresult != ACLCHECK_OK)
     733                 :           8 :         aclcheck_error(aclresult, OBJECT_DATABASE,
     734                 :           4 :                        get_database_name(MyDatabaseId));
     735                 :             : 
     736                 :             :     /*
     737                 :             :      * Non-superusers are required to set a password for authentication, and
     738                 :             :      * that password must be used by the target server, but the superuser can
     739                 :             :      * exempt a subscription from this requirement.
     740                 :             :      */
     741   [ +  +  +  + ]:         251 :     if (!opts.passwordrequired && !superuser_arg(owner))
     742         [ +  - ]:           4 :         ereport(ERROR,
     743                 :             :                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
     744                 :             :                  errmsg("password_required=false is superuser-only"),
     745                 :             :                  errhint("Subscriptions with the password_required option set to false may only be created or modified by the superuser.")));
     746                 :             : 
     747                 :             :     /*
     748                 :             :      * If built with appropriate switch, whine when regression-testing
     749                 :             :      * conventions for subscription names are violated.
     750                 :             :      */
     751                 :             : #ifdef ENFORCE_REGRESSION_TEST_NAME_RESTRICTIONS
     752                 :             :     if (strncmp(stmt->subname, "regress_", 8) != 0)
     753                 :             :         elog(WARNING, "subscriptions created by regression test cases should have names starting with \"regress_\"");
     754                 :             : #endif
     755                 :             : 
     756                 :         247 :     rel = table_open(SubscriptionRelationId, RowExclusiveLock);
     757                 :             : 
     758                 :             :     /* Check if name is used */
     759                 :         247 :     subid = GetSysCacheOid2(SUBSCRIPTIONNAME, Anum_pg_subscription_oid,
     760                 :             :                             ObjectIdGetDatum(MyDatabaseId), CStringGetDatum(stmt->subname));
     761         [ +  + ]:         247 :     if (OidIsValid(subid))
     762                 :             :     {
     763         [ +  - ]:           5 :         ereport(ERROR,
     764                 :             :                 (errcode(ERRCODE_DUPLICATE_OBJECT),
     765                 :             :                  errmsg("subscription \"%s\" already exists",
     766                 :             :                         stmt->subname)));
     767                 :             :     }
     768                 :             : 
     769                 :             :     /*
     770                 :             :      * Ensure that system configuration parameters are set appropriately to
     771                 :             :      * support retain_dead_tuples and max_retention_duration.
     772                 :             :      */
     773                 :         242 :     CheckSubDeadTupleRetention(true, !opts.enabled, WARNING,
     774                 :         242 :                                opts.retaindeadtuples, opts.retaindeadtuples,
     775                 :         242 :                                (opts.maxretention > 0));
     776                 :             : 
     777         [ +  + ]:         242 :     if (!IsSet(opts.specified_opts, SUBOPT_SLOT_NAME) &&
     778         [ +  - ]:         199 :         opts.slot_name == NULL)
     779                 :         199 :         opts.slot_name = stmt->subname;
     780                 :             : 
     781                 :             :     /* The default for synchronous_commit of subscriptions is off. */
     782         [ +  - ]:         242 :     if (opts.synchronous_commit == NULL)
     783                 :         242 :         opts.synchronous_commit = "off";
     784                 :             : 
     785                 :             :     /*
     786                 :             :      * The default for wal_receiver_timeout of subscriptions is -1, which
     787                 :             :      * means the value is inherited from the server configuration, command
     788                 :             :      * line, or role/database settings.
     789                 :             :      */
     790         [ +  - ]:         242 :     if (opts.wal_receiver_timeout == NULL)
     791                 :         242 :         opts.wal_receiver_timeout = "-1";
     792                 :             : 
     793                 :             :     /* Load the library providing us libpq calls. */
     794                 :         242 :     load_file("libpqwalreceiver", false);
     795                 :             : 
     796         [ +  + ]:         242 :     if (stmt->servername)
     797                 :             :     {
     798                 :             :         ForeignServer *server;
     799                 :             : 
     800                 :             :         Assert(!stmt->conninfo);
     801                 :             : 
     802                 :          20 :         server = GetForeignServerByName(stmt->servername, false);
     803                 :          20 :         serverid = server->serverid;
     804                 :             : 
     805                 :             :         /* check USAGE privileges on server */
     806                 :          20 :         aclresult = object_aclcheck(ForeignServerRelationId, serverid, owner, ACL_USAGE);
     807         [ +  + ]:          20 :         if (aclresult != ACLCHECK_OK)
     808                 :           4 :             aclcheck_error(aclresult, OBJECT_FOREIGN_SERVER, server->servername);
     809                 :             : 
     810                 :             :         /* check user mapping */
     811                 :          16 :         GetUserMappingExtended(owner, server->serverid, WARNING);
     812                 :             : 
     813                 :             :         /*
     814                 :             :          * Check conninfo if connecting; otherwise only check that the
     815                 :             :          * server's FDW supports connections.
     816                 :             :          */
     817         [ +  + ]:          16 :         if (opts.connect)
     818                 :             :         {
     819                 :           2 :             conninfo = ForeignServerConnectionString(owner, server);
     820   [ -  +  -  - ]:           1 :             walrcv_check_conninfo(conninfo, opts.passwordrequired && !superuser());
     821                 :             :         }
     822                 :             :         else
     823                 :             :         {
     824                 :          14 :             ForeignDataWrapper *fdw = GetForeignDataWrapper(server->fdwid);
     825                 :             : 
     826         [ +  + ]:          14 :             if (!OidIsValid(fdw->fdwconnection))
     827         [ +  - ]:           4 :                 ereport(ERROR,
     828                 :             :                         (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     829                 :             :                          errmsg("foreign-data wrapper \"%s\" does not support subscription connections",
     830                 :             :                                 fdw->fdwname),
     831                 :             :                          errdetail("Foreign-data wrapper must be defined with CONNECTION specified.")));
     832                 :             :         }
     833                 :             :     }
     834                 :             :     else
     835                 :             :     {
     836                 :             :         Assert(stmt->conninfo);
     837                 :             : 
     838                 :         222 :         conninfo = stmt->conninfo;
     839   [ +  +  +  + ]:         222 :         walrcv_check_conninfo(conninfo, opts.passwordrequired && !superuser());
     840                 :             :     }
     841                 :             : 
     842                 :         221 :     publications = stmt->publication;
     843                 :             : 
     844                 :             :     /* Everything ok, form a new tuple. */
     845                 :         221 :     memset(values, 0, sizeof(values));
     846                 :         221 :     memset(nulls, false, sizeof(nulls));
     847                 :             : 
     848                 :         221 :     subid = GetNewOidWithIndex(rel, SubscriptionObjectIndexId,
     849                 :             :                                Anum_pg_subscription_oid);
     850                 :         221 :     values[Anum_pg_subscription_oid - 1] = ObjectIdGetDatum(subid);
     851                 :         221 :     values[Anum_pg_subscription_subdbid - 1] = ObjectIdGetDatum(MyDatabaseId);
     852                 :         221 :     values[Anum_pg_subscription_subskiplsn - 1] = LSNGetDatum(InvalidXLogRecPtr);
     853                 :         221 :     values[Anum_pg_subscription_subname - 1] =
     854                 :         221 :         DirectFunctionCall1(namein, CStringGetDatum(stmt->subname));
     855                 :         221 :     values[Anum_pg_subscription_subowner - 1] = ObjectIdGetDatum(owner);
     856                 :         221 :     values[Anum_pg_subscription_subenabled - 1] = BoolGetDatum(opts.enabled);
     857                 :         221 :     values[Anum_pg_subscription_subbinary - 1] = BoolGetDatum(opts.binary);
     858                 :         221 :     values[Anum_pg_subscription_substream - 1] = CharGetDatum(opts.streaming);
     859                 :         221 :     values[Anum_pg_subscription_subtwophasestate - 1] =
     860         [ +  + ]:         221 :         CharGetDatum(opts.twophase ?
     861                 :             :                      LOGICALREP_TWOPHASE_STATE_PENDING :
     862                 :             :                      LOGICALREP_TWOPHASE_STATE_DISABLED);
     863                 :         221 :     values[Anum_pg_subscription_subdisableonerr - 1] = BoolGetDatum(opts.disableonerr);
     864                 :         221 :     values[Anum_pg_subscription_subpasswordrequired - 1] = BoolGetDatum(opts.passwordrequired);
     865                 :         221 :     values[Anum_pg_subscription_subrunasowner - 1] = BoolGetDatum(opts.runasowner);
     866                 :         221 :     values[Anum_pg_subscription_subfailover - 1] = BoolGetDatum(opts.failover);
     867                 :         221 :     values[Anum_pg_subscription_subretaindeadtuples - 1] =
     868                 :         221 :         BoolGetDatum(opts.retaindeadtuples);
     869                 :         221 :     values[Anum_pg_subscription_submaxretention - 1] =
     870                 :         221 :         Int32GetDatum(opts.maxretention);
     871                 :         221 :     values[Anum_pg_subscription_subretentionactive - 1] =
     872                 :         221 :         BoolGetDatum(opts.retaindeadtuples);
     873                 :         221 :     values[Anum_pg_subscription_subserver - 1] = ObjectIdGetDatum(serverid);
     874         [ +  + ]:         221 :     if (!OidIsValid(serverid))
     875                 :         210 :         values[Anum_pg_subscription_subconninfo - 1] =
     876                 :         210 :             CStringGetTextDatum(conninfo);
     877                 :             :     else
     878                 :          11 :         nulls[Anum_pg_subscription_subconninfo - 1] = true;
     879         [ +  + ]:         221 :     if (opts.slot_name)
     880                 :         206 :         values[Anum_pg_subscription_subslotname - 1] =
     881                 :         206 :             DirectFunctionCall1(namein, CStringGetDatum(opts.slot_name));
     882                 :             :     else
     883                 :          15 :         nulls[Anum_pg_subscription_subslotname - 1] = true;
     884                 :         221 :     values[Anum_pg_subscription_subsynccommit - 1] =
     885                 :         221 :         CStringGetTextDatum(opts.synchronous_commit);
     886                 :         221 :     values[Anum_pg_subscription_subwalrcvtimeout - 1] =
     887                 :         221 :         CStringGetTextDatum(opts.wal_receiver_timeout);
     888                 :         217 :     values[Anum_pg_subscription_subpublications - 1] =
     889                 :         221 :         publicationListToArray(publications);
     890                 :         217 :     values[Anum_pg_subscription_suborigin - 1] =
     891                 :         217 :         CStringGetTextDatum(opts.origin);
     892                 :             : 
     893                 :         217 :     values[Anum_pg_subscription_subconflictlogdest - 1] =
     894                 :         217 :         CStringGetTextDatum(ConflictLogDestNames[opts.conflictlogdest]);
     895                 :             : 
     896                 :             :     /*
     897                 :             :      * We create the conflict log table here, if required, so that its
     898                 :             :      * relation OID can be stored when inserting the pg_subscription tuple
     899                 :             :      * below.
     900                 :             :      */
     901   [ +  +  +  + ]:         217 :     if (CONFLICTS_LOGGED_TO_TABLE(opts.conflictlogdest))
     902                 :          10 :         logrelid = create_conflict_log_table(subid, stmt->subname, owner);
     903                 :             : 
     904                 :             :     /* Store table OID in the catalog. */
     905                 :         217 :     values[Anum_pg_subscription_subconflictlogrelid - 1] =
     906                 :         217 :         ObjectIdGetDatum(logrelid);
     907                 :             : 
     908                 :         217 :     tup = heap_form_tuple(RelationGetDescr(rel), values, nulls);
     909                 :             : 
     910                 :             :     /* Insert tuple into catalog. */
     911                 :         217 :     CatalogTupleInsert(rel, tup);
     912                 :         217 :     heap_freetuple(tup);
     913                 :             : 
     914                 :         217 :     recordDependencyOnOwner(SubscriptionRelationId, subid, owner);
     915                 :             : 
     916                 :         217 :     ObjectAddressSet(myself, SubscriptionRelationId, subid);
     917                 :             : 
     918         [ +  + ]:         217 :     if (stmt->servername)
     919                 :             :     {
     920                 :             :         ObjectAddress referenced;
     921                 :             : 
     922                 :             :         Assert(OidIsValid(serverid));
     923                 :             : 
     924                 :          11 :         ObjectAddressSet(referenced, ForeignServerRelationId, serverid);
     925                 :          11 :         recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
     926                 :             :     }
     927                 :             : 
     928                 :             :     /*
     929                 :             :      * Establish an internal dependency between the conflict log table and the
     930                 :             :      * subscription.
     931                 :             :      *
     932                 :             :      * We use DEPENDENCY_INTERNAL to signify that the table's lifecycle is
     933                 :             :      * strictly tied to the subscription, similar to how a TOAST table relates
     934                 :             :      * to its main table or a sequence relates to an identity column.
     935                 :             :      *
     936                 :             :      * This ensures the conflict log table is automatically reaped during a
     937                 :             :      * DROP SUBSCRIPTION via performDeletion().
     938                 :             :      */
     939         [ +  + ]:         217 :     if (OidIsValid(logrelid))
     940                 :             :     {
     941                 :             :         ObjectAddress cltaddr;
     942                 :             : 
     943                 :          10 :         ObjectAddressSet(cltaddr, RelationRelationId, logrelid);
     944                 :          10 :         recordDependencyOn(&cltaddr, &myself, DEPENDENCY_INTERNAL);
     945                 :             :     }
     946                 :             : 
     947                 :             :     /*
     948                 :             :      * A replication origin is currently created for all subscriptions,
     949                 :             :      * including those that only contain sequences or are otherwise empty.
     950                 :             :      *
     951                 :             :      * XXX: While this is technically unnecessary, optimizing it would require
     952                 :             :      * additional logic to skip origin creation during DDL operations and
     953                 :             :      * apply workers initialization, and to handle origin creation dynamically
     954                 :             :      * when tables are added to the subscription. It is not clear whether
     955                 :             :      * preventing creation of origins is worth additional complexity.
     956                 :             :      */
     957                 :         217 :     ReplicationOriginNameForLogicalRep(subid, InvalidOid, originname, sizeof(originname));
     958                 :         217 :     replorigin_create(originname);
     959                 :             : 
     960                 :             :     /*
     961                 :             :      * Connect to remote side to execute requested commands and fetch table
     962                 :             :      * and sequence info.
     963                 :             :      */
     964         [ +  + ]:         217 :     if (opts.connect)
     965                 :             :     {
     966                 :             :         char       *err;
     967                 :             :         WalReceiverConn *wrconn;
     968                 :             :         bool        must_use_password;
     969                 :             : 
     970                 :             :         /* Try to connect to the publisher. */
     971   [ -  +  -  - ]:         130 :         must_use_password = !superuser_arg(owner) && opts.passwordrequired;
     972                 :         130 :         wrconn = walrcv_connect(conninfo, true, true, must_use_password,
     973                 :             :                                 stmt->subname, &err);
     974         [ +  + ]:         130 :         if (!wrconn)
     975         [ +  - ]:           4 :             ereport(ERROR,
     976                 :             :                     (errcode(ERRCODE_CONNECTION_FAILURE),
     977                 :             :                      errmsg("subscription \"%s\" could not connect to the publisher: %s",
     978                 :             :                             stmt->subname, err)));
     979                 :             : 
     980         [ +  + ]:         126 :         PG_TRY();
     981                 :             :         {
     982                 :         126 :             bool        has_tables = false;
     983                 :             :             List       *pubrels;
     984                 :             :             char        relation_state;
     985                 :             : 
     986                 :         126 :             check_publications(wrconn, publications);
     987                 :         126 :             check_publications_origin_tables(wrconn, publications,
     988                 :         126 :                                              opts.copy_data,
     989                 :         126 :                                              opts.retaindeadtuples, opts.origin,
     990                 :             :                                              NULL, 0, stmt->subname);
     991                 :         126 :             check_publications_origin_sequences(wrconn, publications,
     992                 :         126 :                                                 opts.copy_data, opts.origin,
     993                 :             :                                                 NULL, 0, stmt->subname);
     994                 :             : 
     995         [ +  + ]:         126 :             if (opts.retaindeadtuples)
     996                 :           3 :                 CheckPubDeadTupleRetention(wrconn);
     997                 :             : 
     998                 :             :             /*
     999                 :             :              * Set sync state based on if we were asked to do data copy or
    1000                 :             :              * not.
    1001                 :             :              */
    1002         [ +  + ]:         126 :             relation_state = opts.copy_data ? SUBREL_STATE_INIT : SUBREL_STATE_READY;
    1003                 :             : 
    1004                 :             :             /*
    1005                 :             :              * Build local relation status info. Relations are for both tables
    1006                 :             :              * and sequences from the publisher.
    1007                 :             :              */
    1008                 :         126 :             pubrels = fetch_relation_list(wrconn, publications);
    1009                 :             : 
    1010   [ +  +  +  +  :         445 :             foreach_ptr(PublicationRelKind, pubrelinfo, pubrels)
                   +  + ]
    1011                 :             :             {
    1012                 :             :                 Oid         relid;
    1013                 :             :                 char        relkind;
    1014                 :         195 :                 RangeVar   *rv = pubrelinfo->rv;
    1015                 :             : 
    1016                 :         195 :                 relid = RangeVarGetRelid(rv, AccessShareLock, false);
    1017                 :         195 :                 relkind = get_rel_relkind(relid);
    1018                 :             : 
    1019                 :             :                 /* Check for supported relkind. */
    1020                 :         195 :                 CheckSubscriptionRelkind(relkind, pubrelinfo->relkind,
    1021                 :         195 :                                          rv->schemaname, rv->relname);
    1022                 :         195 :                 has_tables |= (relkind != RELKIND_SEQUENCE);
    1023                 :         195 :                 AddSubscriptionRelState(subid, relid, relation_state,
    1024                 :             :                                         InvalidXLogRecPtr, true);
    1025                 :             :             }
    1026                 :             : 
    1027                 :             :             /*
    1028                 :             :              * If requested, create permanent slot for the subscription. We
    1029                 :             :              * won't use the initial snapshot for anything, so no need to
    1030                 :             :              * export it.
    1031                 :             :              *
    1032                 :             :              * XXX: Similar to origins, it is not clear whether preventing the
    1033                 :             :              * slot creation for empty and sequence-only subscriptions is
    1034                 :             :              * worth additional complexity.
    1035                 :             :              */
    1036         [ +  + ]:         125 :             if (opts.create_slot)
    1037                 :             :             {
    1038                 :         120 :                 bool        twophase_enabled = false;
    1039                 :             : 
    1040                 :             :                 Assert(opts.slot_name);
    1041                 :             : 
    1042                 :             :                 /*
    1043                 :             :                  * Even if two_phase is set, don't create the slot with
    1044                 :             :                  * two-phase enabled. Will enable it once all the tables are
    1045                 :             :                  * synced and ready. This avoids race-conditions like prepared
    1046                 :             :                  * transactions being skipped due to changes not being applied
    1047                 :             :                  * due to checks in should_apply_changes_for_rel() when
    1048                 :             :                  * tablesync for the corresponding tables are in progress. See
    1049                 :             :                  * comments atop worker.c.
    1050                 :             :                  *
    1051                 :             :                  * Note that if tables were specified but copy_data is false
    1052                 :             :                  * then it is safe to enable two_phase up-front because those
    1053                 :             :                  * tables are already initially in READY state. When the
    1054                 :             :                  * subscription has no tables, we leave the twophase state as
    1055                 :             :                  * PENDING, to allow ALTER SUBSCRIPTION ... REFRESH
    1056                 :             :                  * PUBLICATION to work.
    1057                 :             :                  */
    1058   [ +  +  +  +  :         120 :                 if (opts.twophase && !opts.copy_data && has_tables)
                   +  - ]
    1059                 :           1 :                     twophase_enabled = true;
    1060                 :             : 
    1061                 :         120 :                 walrcv_create_slot(wrconn, opts.slot_name, false, twophase_enabled,
    1062                 :             :                                    opts.failover, CRS_NOEXPORT_SNAPSHOT, NULL);
    1063                 :             : 
    1064         [ +  + ]:         120 :                 if (twophase_enabled)
    1065                 :           1 :                     UpdateTwoPhaseState(subid, LOGICALREP_TWOPHASE_STATE_ENABLED);
    1066                 :             : 
    1067         [ +  - ]:         120 :                 ereport(NOTICE,
    1068                 :             :                         (errmsg("created replication slot \"%s\" on publisher",
    1069                 :             :                                 opts.slot_name)));
    1070                 :             :             }
    1071                 :             :         }
    1072                 :           1 :         PG_FINALLY();
    1073                 :             :         {
    1074                 :         126 :             walrcv_disconnect(wrconn);
    1075                 :             :         }
    1076         [ +  + ]:         126 :         PG_END_TRY();
    1077                 :             :     }
    1078                 :             :     else
    1079         [ +  - ]:          87 :         ereport(WARNING,
    1080                 :             :                 (errmsg("subscription was created, but is not connected"),
    1081                 :             :                  errhint("To initiate replication, you must manually create the replication slot, enable the subscription, and alter the subscription to refresh publications.")));
    1082                 :             : 
    1083                 :         212 :     table_close(rel, RowExclusiveLock);
    1084                 :             : 
    1085                 :         212 :     pgstat_create_subscription(subid);
    1086                 :             : 
    1087                 :             :     /*
    1088                 :             :      * Notify the launcher to start the apply worker if the subscription is
    1089                 :             :      * enabled, or to create the conflict detection slot if retain_dead_tuples
    1090                 :             :      * is enabled.
    1091                 :             :      *
    1092                 :             :      * Creating the conflict detection slot is essential even when the
    1093                 :             :      * subscription is not enabled. This ensures that dead tuples are
    1094                 :             :      * retained, which is necessary for accurately identifying the type of
    1095                 :             :      * conflict during replication.
    1096                 :             :      */
    1097   [ +  +  +  + ]:         212 :     if (opts.enabled || opts.retaindeadtuples)
    1098                 :         119 :         ApplyLauncherWakeupAtCommit();
    1099                 :             : 
    1100         [ -  + ]:         212 :     InvokeObjectPostCreateHook(SubscriptionRelationId, subid, 0);
    1101                 :             : 
    1102                 :         212 :     return myself;
    1103                 :             : }
    1104                 :             : 
    1105                 :             : static void
    1106                 :          39 : AlterSubscription_refresh(Subscription *sub, bool copy_data,
    1107                 :             :                           List *validate_publications, char *conninfo)
    1108                 :             : {
    1109                 :             :     char       *err;
    1110                 :          39 :     List       *pubrels = NIL;
    1111                 :             :     Oid        *pubrel_local_oids;
    1112                 :             :     List       *subrel_states;
    1113                 :          39 :     List       *sub_remove_rels = NIL;
    1114                 :             :     Oid        *subrel_local_oids;
    1115                 :             :     Oid        *subseq_local_oids;
    1116                 :             :     int         subrel_count;
    1117                 :             :     ListCell   *lc;
    1118                 :             :     int         off;
    1119                 :          39 :     int         tbl_count = 0;
    1120                 :          39 :     int         seq_count = 0;
    1121                 :          39 :     Relation    rel = NULL;
    1122                 :             :     typedef struct SubRemoveRels
    1123                 :             :     {
    1124                 :             :         Oid         relid;
    1125                 :             :         char        state;
    1126                 :             :     } SubRemoveRels;
    1127                 :             : 
    1128                 :             :     WalReceiverConn *wrconn;
    1129                 :             :     bool        must_use_password;
    1130                 :             : 
    1131                 :             :     /*
    1132                 :             :      * Should not happen: CREATE/ALTER/DROP SUBSCRIPTION did not call
    1133                 :             :      * SubscriptionConninfo() in a path where it's required.
    1134                 :             :      */
    1135         [ -  + ]:          39 :     if (!conninfo)
    1136         [ #  # ]:           0 :         elog(ERROR, "no connection string provided for subscription");
    1137                 :             : 
    1138                 :             :     /* Load the library providing us libpq calls. */
    1139                 :          39 :     load_file("libpqwalreceiver", false);
    1140                 :             : 
    1141                 :             :     /* Try to connect to the publisher. */
    1142   [ +  -  +  + ]:          39 :     must_use_password = sub->passwordrequired && !sub->ownersuperuser;
    1143                 :          39 :     wrconn = walrcv_connect(conninfo, true, true, must_use_password,
    1144                 :             :                             sub->name, &err);
    1145         [ -  + ]:          38 :     if (!wrconn)
    1146         [ #  # ]:           0 :         ereport(ERROR,
    1147                 :             :                 (errcode(ERRCODE_CONNECTION_FAILURE),
    1148                 :             :                  errmsg("subscription \"%s\" could not connect to the publisher: %s",
    1149                 :             :                         sub->name, err)));
    1150                 :             : 
    1151         [ +  - ]:          38 :     PG_TRY();
    1152                 :             :     {
    1153         [ +  + ]:          38 :         if (validate_publications)
    1154                 :           9 :             check_publications(wrconn, validate_publications);
    1155                 :             : 
    1156                 :             :         /* Get the relation list from publisher. */
    1157                 :          38 :         pubrels = fetch_relation_list(wrconn, sub->publications);
    1158                 :             : 
    1159                 :             :         /* Get local relation list. */
    1160                 :          38 :         subrel_states = GetSubscriptionRelations(sub->oid, true, true, false);
    1161                 :          38 :         subrel_count = list_length(subrel_states);
    1162                 :             : 
    1163                 :             :         /*
    1164                 :             :          * Build qsorted arrays of local table oids and sequence oids for
    1165                 :             :          * faster lookup. This can potentially contain all tables and
    1166                 :             :          * sequences in the database so speed of lookup is important.
    1167                 :             :          *
    1168                 :             :          * We do not yet know the exact count of tables and sequences, so we
    1169                 :             :          * allocate separate arrays for table OIDs and sequence OIDs based on
    1170                 :             :          * the total number of relations (subrel_count).
    1171                 :             :          */
    1172                 :          38 :         subrel_local_oids = palloc(subrel_count * sizeof(Oid));
    1173                 :          38 :         subseq_local_oids = palloc(subrel_count * sizeof(Oid));
    1174   [ +  +  +  +  :         136 :         foreach(lc, subrel_states)
                   +  + ]
    1175                 :             :         {
    1176                 :          98 :             SubscriptionRelState *relstate = (SubscriptionRelState *) lfirst(lc);
    1177                 :             : 
    1178         [ +  + ]:          98 :             if (get_rel_relkind(relstate->relid) == RELKIND_SEQUENCE)
    1179                 :           9 :                 subseq_local_oids[seq_count++] = relstate->relid;
    1180                 :             :             else
    1181                 :          89 :                 subrel_local_oids[tbl_count++] = relstate->relid;
    1182                 :             :         }
    1183                 :             : 
    1184                 :          38 :         qsort(subrel_local_oids, tbl_count, sizeof(Oid), oid_cmp);
    1185                 :          38 :         check_publications_origin_tables(wrconn, sub->publications, copy_data,
    1186                 :          38 :                                          sub->retaindeadtuples, sub->origin,
    1187                 :             :                                          subrel_local_oids, tbl_count,
    1188                 :             :                                          sub->name);
    1189                 :             : 
    1190                 :          38 :         qsort(subseq_local_oids, seq_count, sizeof(Oid), oid_cmp);
    1191                 :          38 :         check_publications_origin_sequences(wrconn, sub->publications,
    1192                 :             :                                             copy_data, sub->origin,
    1193                 :             :                                             subseq_local_oids, seq_count,
    1194                 :             :                                             sub->name);
    1195                 :             : 
    1196                 :             :         /*
    1197                 :             :          * Walk over the remote relations and try to match them to locally
    1198                 :             :          * known relations. If the relation is not known locally create a new
    1199                 :             :          * state for it.
    1200                 :             :          *
    1201                 :             :          * Also builds array of local oids of remote relations for the next
    1202                 :             :          * step.
    1203                 :             :          */
    1204                 :          38 :         off = 0;
    1205                 :          38 :         pubrel_local_oids = palloc(list_length(pubrels) * sizeof(Oid));
    1206                 :             : 
    1207   [ +  +  +  +  :         183 :         foreach_ptr(PublicationRelKind, pubrelinfo, pubrels)
                   +  + ]
    1208                 :             :         {
    1209                 :         107 :             RangeVar   *rv = pubrelinfo->rv;
    1210                 :             :             Oid         relid;
    1211                 :             :             char        relkind;
    1212                 :             : 
    1213                 :         107 :             relid = RangeVarGetRelid(rv, AccessShareLock, false);
    1214                 :         107 :             relkind = get_rel_relkind(relid);
    1215                 :             : 
    1216                 :             :             /* Check for supported relkind. */
    1217                 :         107 :             CheckSubscriptionRelkind(relkind, pubrelinfo->relkind,
    1218                 :         107 :                                      rv->schemaname, rv->relname);
    1219                 :             : 
    1220                 :         107 :             pubrel_local_oids[off++] = relid;
    1221                 :             : 
    1222         [ +  + ]:         107 :             if (!bsearch(&relid, subrel_local_oids,
    1223                 :          39 :                          tbl_count, sizeof(Oid), oid_cmp) &&
    1224         [ +  + ]:          39 :                 !bsearch(&relid, subseq_local_oids,
    1225                 :             :                          seq_count, sizeof(Oid), oid_cmp))
    1226                 :             :             {
    1227         [ +  + ]:          30 :                 AddSubscriptionRelState(sub->oid, relid,
    1228                 :             :                                         copy_data ? SUBREL_STATE_INIT : SUBREL_STATE_READY,
    1229                 :             :                                         InvalidXLogRecPtr, true);
    1230   [ +  +  -  + ]:          30 :                 ereport(DEBUG1,
    1231                 :             :                         errmsg_internal("%s \"%s.%s\" added to subscription \"%s\"",
    1232                 :             :                                         relkind == RELKIND_SEQUENCE ? "sequence" : "table",
    1233                 :             :                                         rv->schemaname, rv->relname, sub->name));
    1234                 :             :             }
    1235                 :             :         }
    1236                 :             : 
    1237                 :             :         /*
    1238                 :             :          * Next remove state for tables we should not care about anymore using
    1239                 :             :          * the data we collected above
    1240                 :             :          */
    1241                 :          38 :         qsort(pubrel_local_oids, list_length(pubrels), sizeof(Oid), oid_cmp);
    1242                 :             : 
    1243         [ +  + ]:         127 :         for (off = 0; off < tbl_count; off++)
    1244                 :             :         {
    1245                 :          89 :             Oid         relid = subrel_local_oids[off];
    1246                 :             : 
    1247         [ +  + ]:          89 :             if (!bsearch(&relid, pubrel_local_oids,
    1248                 :          89 :                          list_length(pubrels), sizeof(Oid), oid_cmp))
    1249                 :             :             {
    1250                 :             :                 char        state;
    1251                 :             :                 XLogRecPtr  statelsn;
    1252                 :          21 :                 SubRemoveRels *remove_rel = palloc_object(SubRemoveRels);
    1253                 :             : 
    1254                 :             :                 /*
    1255                 :             :                  * Lock pg_subscription_rel with AccessExclusiveLock to
    1256                 :             :                  * prevent any race conditions with the apply worker
    1257                 :             :                  * re-launching workers at the same time this code is trying
    1258                 :             :                  * to remove those tables.
    1259                 :             :                  *
    1260                 :             :                  * Even if new worker for this particular rel is restarted it
    1261                 :             :                  * won't be able to make any progress as we hold exclusive
    1262                 :             :                  * lock on pg_subscription_rel till the transaction end. It
    1263                 :             :                  * will simply exit as there is no corresponding rel entry.
    1264                 :             :                  *
    1265                 :             :                  * This locking also ensures that the state of rels won't
    1266                 :             :                  * change till we are done with this refresh operation.
    1267                 :             :                  */
    1268         [ +  + ]:          21 :                 if (!rel)
    1269                 :           9 :                     rel = table_open(SubscriptionRelRelationId, AccessExclusiveLock);
    1270                 :             : 
    1271                 :             :                 /* Last known rel state. */
    1272                 :          21 :                 state = GetSubscriptionRelState(sub->oid, relid, &statelsn);
    1273                 :             : 
    1274                 :          21 :                 RemoveSubscriptionRel(sub->oid, relid);
    1275                 :             : 
    1276                 :          21 :                 remove_rel->relid = relid;
    1277                 :          21 :                 remove_rel->state = state;
    1278                 :             : 
    1279                 :          21 :                 sub_remove_rels = lappend(sub_remove_rels, remove_rel);
    1280                 :             : 
    1281                 :          21 :                 logicalrep_worker_stop(WORKERTYPE_TABLESYNC, sub->oid, relid);
    1282                 :             : 
    1283                 :             :                 /*
    1284                 :             :                  * For READY state, we would have already dropped the
    1285                 :             :                  * tablesync origin.
    1286                 :             :                  */
    1287         [ -  + ]:          21 :                 if (state != SUBREL_STATE_READY)
    1288                 :             :                 {
    1289                 :             :                     char        originname[NAMEDATALEN];
    1290                 :             : 
    1291                 :             :                     /*
    1292                 :             :                      * Drop the tablesync's origin tracking if exists.
    1293                 :             :                      *
    1294                 :             :                      * It is possible that the origin is not yet created for
    1295                 :             :                      * tablesync worker, this can happen for the states before
    1296                 :             :                      * SUBREL_STATE_DATASYNC. The tablesync worker or apply
    1297                 :             :                      * worker can also concurrently try to drop the origin and
    1298                 :             :                      * by this time the origin might be already removed. For
    1299                 :             :                      * these reasons, passing missing_ok = true.
    1300                 :             :                      */
    1301                 :           0 :                     ReplicationOriginNameForLogicalRep(sub->oid, relid, originname,
    1302                 :             :                                                        sizeof(originname));
    1303                 :           0 :                     replorigin_drop_by_name(originname, true, false);
    1304                 :             :                 }
    1305                 :             : 
    1306         [ +  + ]:          21 :                 ereport(DEBUG1,
    1307                 :             :                         (errmsg_internal("table \"%s.%s\" removed from subscription \"%s\"",
    1308                 :             :                                          get_namespace_name(get_rel_namespace(relid)),
    1309                 :             :                                          get_rel_name(relid),
    1310                 :             :                                          sub->name)));
    1311                 :             :             }
    1312                 :             :         }
    1313                 :             : 
    1314                 :             :         /*
    1315                 :             :          * Next remove state for sequences we should not care about anymore
    1316                 :             :          * using the data we collected above
    1317                 :             :          */
    1318         [ +  + ]:          47 :         for (off = 0; off < seq_count; off++)
    1319                 :             :         {
    1320                 :           9 :             Oid         relid = subseq_local_oids[off];
    1321                 :             : 
    1322         [ -  + ]:           9 :             if (!bsearch(&relid, pubrel_local_oids,
    1323                 :           9 :                          list_length(pubrels), sizeof(Oid), oid_cmp))
    1324                 :             :             {
    1325                 :             :                 /*
    1326                 :             :                  * This locking ensures that the state of rels won't change
    1327                 :             :                  * till we are done with this refresh operation.
    1328                 :             :                  */
    1329         [ #  # ]:           0 :                 if (!rel)
    1330                 :           0 :                     rel = table_open(SubscriptionRelRelationId, AccessExclusiveLock);
    1331                 :             : 
    1332                 :           0 :                 RemoveSubscriptionRel(sub->oid, relid);
    1333                 :             : 
    1334         [ #  # ]:           0 :                 ereport(DEBUG1,
    1335                 :             :                         errmsg_internal("sequence \"%s.%s\" removed from subscription \"%s\"",
    1336                 :             :                                         get_namespace_name(get_rel_namespace(relid)),
    1337                 :             :                                         get_rel_name(relid),
    1338                 :             :                                         sub->name));
    1339                 :             :             }
    1340                 :             :         }
    1341                 :             : 
    1342                 :             :         /*
    1343                 :             :          * Drop the tablesync slots associated with removed tables. This has
    1344                 :             :          * to be at the end because otherwise if there is an error while doing
    1345                 :             :          * the database operations we won't be able to rollback dropped slots.
    1346                 :             :          */
    1347   [ +  +  +  +  :          97 :         foreach_ptr(SubRemoveRels, sub_remove_rel, sub_remove_rels)
                   +  + ]
    1348                 :             :         {
    1349         [ -  + ]:          21 :             if (sub_remove_rel->state != SUBREL_STATE_READY &&
    1350         [ #  # ]:           0 :                 sub_remove_rel->state != SUBREL_STATE_SYNCDONE)
    1351                 :             :             {
    1352                 :           0 :                 char        syncslotname[NAMEDATALEN] = {0};
    1353                 :             : 
    1354                 :             :                 /*
    1355                 :             :                  * For READY/SYNCDONE states we know the tablesync slot has
    1356                 :             :                  * already been dropped by the tablesync worker.
    1357                 :             :                  *
    1358                 :             :                  * For other states, there is no certainty, maybe the slot
    1359                 :             :                  * does not exist yet. Also, if we fail after removing some of
    1360                 :             :                  * the slots, next time, it will again try to drop already
    1361                 :             :                  * dropped slots and fail. For these reasons, we allow
    1362                 :             :                  * missing_ok = true for the drop.
    1363                 :             :                  */
    1364                 :           0 :                 ReplicationSlotNameForTablesync(sub->oid, sub_remove_rel->relid,
    1365                 :             :                                                 syncslotname, sizeof(syncslotname));
    1366                 :           0 :                 ReplicationSlotDropAtPubNode(wrconn, syncslotname, true);
    1367                 :             :             }
    1368                 :             :         }
    1369                 :             :     }
    1370                 :           0 :     PG_FINALLY();
    1371                 :             :     {
    1372                 :          38 :         walrcv_disconnect(wrconn);
    1373                 :             :     }
    1374         [ -  + ]:          38 :     PG_END_TRY();
    1375                 :             : 
    1376         [ +  + ]:          38 :     if (rel)
    1377                 :           9 :         table_close(rel, NoLock);
    1378                 :          38 : }
    1379                 :             : 
    1380                 :             : /*
    1381                 :             :  * Marks all sequences with INIT state.
    1382                 :             :  */
    1383                 :             : static void
    1384                 :           5 : AlterSubscription_refresh_seq(Subscription *sub, char *conninfo)
    1385                 :             : {
    1386                 :           5 :     char       *err = NULL;
    1387                 :             :     WalReceiverConn *wrconn;
    1388                 :             :     bool        must_use_password;
    1389                 :             :     List       *subrel_states;
    1390                 :             : 
    1391                 :             :     /*
    1392                 :             :      * Should not happen: CREATE/ALTER/DROP SUBSCRIPTION did not call
    1393                 :             :      * SubscriptionConninfo() in a path where it's required.
    1394                 :             :      */
    1395         [ -  + ]:           5 :     if (!conninfo)
    1396         [ #  # ]:           0 :         elog(ERROR, "no connection string provided for subscription");
    1397                 :             : 
    1398                 :             :     /* Load the library providing us libpq calls. */
    1399                 :           5 :     load_file("libpqwalreceiver", false);
    1400                 :             : 
    1401                 :             :     /* Try to connect to the publisher. */
    1402   [ +  -  -  + ]:           5 :     must_use_password = sub->passwordrequired && !sub->ownersuperuser;
    1403                 :           5 :     wrconn = walrcv_connect(conninfo, true, true, must_use_password,
    1404                 :             :                             sub->name, &err);
    1405         [ -  + ]:           5 :     if (!wrconn)
    1406         [ #  # ]:           0 :         ereport(ERROR,
    1407                 :             :                 errcode(ERRCODE_CONNECTION_FAILURE),
    1408                 :             :                 errmsg("subscription \"%s\" could not connect to the publisher: %s",
    1409                 :             :                        sub->name, err));
    1410                 :             : 
    1411                 :             :     /* The publisher connection is only needed for the origin check. */
    1412         [ +  - ]:           5 :     PG_TRY();
    1413                 :             :     {
    1414                 :             :         /*
    1415                 :             :          * Sequence synchronization depends on publisher-side functionality
    1416                 :             :          * introduced in PostgreSQL 19, so it cannot work against an older
    1417                 :             :          * publisher.
    1418                 :             :          */
    1419         [ -  + ]:           5 :         if (walrcv_server_version(wrconn) < 190000)
    1420         [ #  # ]:           0 :             ereport(ERROR,
    1421                 :             :                     errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    1422                 :             :                     errmsg("cannot synchronize sequences if the publisher is running a version earlier than PostgreSQL 19"));
    1423                 :             : 
    1424                 :           5 :         check_publications_origin_sequences(wrconn, sub->publications, true,
    1425                 :             :                                             sub->origin, NULL, 0, sub->name);
    1426                 :             :     }
    1427                 :           0 :     PG_FINALLY();
    1428                 :             :     {
    1429                 :           5 :         walrcv_disconnect(wrconn);
    1430                 :             :     }
    1431         [ -  + ]:           5 :     PG_END_TRY();
    1432                 :             : 
    1433                 :             :     /*
    1434                 :             :      * Reset the sequences to INIT so they get re-synchronized with the latest
    1435                 :             :      * publisher values.
    1436                 :             :      *
    1437                 :             :      * A sequence sync worker may already be running. If it has fetched a
    1438                 :             :      * sequence's value from the publisher but not yet marked it READY, it
    1439                 :             :      * must not be allowed to complete that update, as it would overwrite the
    1440                 :             :      * reset below with a stale value and silently lose this refresh request.
    1441                 :             :      * So we stop any running sequence sync worker before resetting the
    1442                 :             :      * states.
    1443                 :             :      *
    1444                 :             :      * This is race-free because AlterSubscription() already holds
    1445                 :             :      * AccessExclusiveLock on the subscription object. That lock blocks a
    1446                 :             :      * running worker's update of sequence state to READY, see
    1447                 :             :      * UpdateSubscriptionRelState() which takes AccessShareLock on the object.
    1448                 :             :      * It also blocks any worker the apply worker re-launches, because a new
    1449                 :             :      * worker takes AccessShareLock on the object before it reads
    1450                 :             :      * pg_subscription_rel, see InitializeLogRepWorker(). Such a worker cannot
    1451                 :             :      * act on the states until we commit, by which time they are reset to INIT
    1452                 :             :      * and it will sync the latest values.
    1453                 :             :      */
    1454                 :             : #ifdef USE_ASSERT_CHECKING
    1455                 :             :     {
    1456                 :             :         LOCKTAG     tag;
    1457                 :             : 
    1458                 :             :         SET_LOCKTAG_OBJECT(tag, InvalidOid, SubscriptionRelationId, sub->oid, 0);
    1459                 :             :         Assert(LockHeldByMe(&tag, AccessExclusiveLock, true));
    1460                 :             :     }
    1461                 :             : #endif
    1462                 :             : 
    1463                 :           5 :     logicalrep_worker_stop(WORKERTYPE_SEQUENCESYNC, sub->oid, InvalidOid);
    1464                 :             : 
    1465                 :             :     /* Reset every local sequence of this subscription to INIT. */
    1466                 :           5 :     subrel_states = GetSubscriptionRelations(sub->oid, false, true, false);
    1467   [ +  -  +  +  :          31 :     foreach_ptr(SubscriptionRelState, subrel, subrel_states)
                   +  + ]
    1468                 :             :     {
    1469                 :          21 :         Oid         relid = subrel->relid;
    1470                 :             : 
    1471                 :          21 :         UpdateSubscriptionRelState(sub->oid, relid, SUBREL_STATE_INIT,
    1472                 :             :                                    InvalidXLogRecPtr, false);
    1473         [ -  + ]:          21 :         ereport(DEBUG1,
    1474                 :             :                 errmsg_internal("sequence \"%s.%s\" of subscription \"%s\" set to INIT state",
    1475                 :             :                                 get_namespace_name(get_rel_namespace(relid)),
    1476                 :             :                                 get_rel_name(relid),
    1477                 :             :                                 sub->name));
    1478                 :             :     }
    1479                 :           5 : }
    1480                 :             : 
    1481                 :             : /*
    1482                 :             :  * Common checks for altering failover, two_phase, and retain_dead_tuples
    1483                 :             :  * options.
    1484                 :             :  */
    1485                 :             : static void
    1486                 :          14 : CheckAlterSubOption(Subscription *sub, const char *option,
    1487                 :             :                     bool slot_needs_update, bool isTopLevel)
    1488                 :             : {
    1489                 :             :     Assert(strcmp(option, "failover") == 0 ||
    1490                 :             :            strcmp(option, "two_phase") == 0 ||
    1491                 :             :            strcmp(option, "retain_dead_tuples") == 0);
    1492                 :             : 
    1493                 :             :     /*
    1494                 :             :      * Altering the retain_dead_tuples option does not update the slot on the
    1495                 :             :      * publisher.
    1496                 :             :      */
    1497                 :             :     Assert(!slot_needs_update || strcmp(option, "retain_dead_tuples") != 0);
    1498                 :             : 
    1499                 :             :     /*
    1500                 :             :      * Do not allow changing the option if the subscription is enabled. This
    1501                 :             :      * is because both failover and two_phase options of the slot on the
    1502                 :             :      * publisher cannot be modified if the slot is currently acquired by the
    1503                 :             :      * existing walsender.
    1504                 :             :      *
    1505                 :             :      * Note that two_phase is enabled (aka changed from 'false' to 'true') on
    1506                 :             :      * the publisher by the existing walsender, so we could have allowed that
    1507                 :             :      * even when the subscription is enabled. But we kept this restriction for
    1508                 :             :      * the sake of consistency and simplicity.
    1509                 :             :      *
    1510                 :             :      * Additionally, do not allow changing the retain_dead_tuples option when
    1511                 :             :      * the subscription is enabled to prevent race conditions arising from the
    1512                 :             :      * new option value being acknowledged asynchronously by the launcher and
    1513                 :             :      * apply workers.
    1514                 :             :      *
    1515                 :             :      * Without the restriction, a race condition may arise when a user
    1516                 :             :      * disables and immediately re-enables the retain_dead_tuples option. In
    1517                 :             :      * this case, the launcher might drop the slot upon noticing the disabled
    1518                 :             :      * action, while the apply worker may keep maintaining
    1519                 :             :      * oldest_nonremovable_xid without noticing the option change. During this
    1520                 :             :      * period, a transaction ID wraparound could falsely make this ID appear
    1521                 :             :      * as if it originates from the future w.r.t the transaction ID stored in
    1522                 :             :      * the slot maintained by launcher.
    1523                 :             :      *
    1524                 :             :      * Similarly, if the user enables retain_dead_tuples concurrently with the
    1525                 :             :      * launcher starting the worker, the apply worker may start calculating
    1526                 :             :      * oldest_nonremovable_xid before the launcher notices the enable action.
    1527                 :             :      * Consequently, the launcher may update slot.xmin to a newer value than
    1528                 :             :      * that maintained by the worker. In subsequent cycles, upon integrating
    1529                 :             :      * the worker's oldest_nonremovable_xid, the launcher might detect a
    1530                 :             :      * retreat in the calculated xmin, necessitating additional handling.
    1531                 :             :      *
    1532                 :             :      * XXX To address the above race conditions, we can define
    1533                 :             :      * oldest_nonremovable_xid as FullTransactionId and adds the check to
    1534                 :             :      * disallow retreating the conflict slot's xmin. For now, we kept the
    1535                 :             :      * implementation simple by disallowing change to the retain_dead_tuples,
    1536                 :             :      * but in the future we can change this after some more analysis.
    1537                 :             :      *
    1538                 :             :      * Note that we could restrict only the enabling of retain_dead_tuples to
    1539                 :             :      * avoid the race conditions described above, but we maintain the
    1540                 :             :      * restriction for both enable and disable operations for the sake of
    1541                 :             :      * consistency.
    1542                 :             :      */
    1543         [ +  + ]:          14 :     if (sub->enabled)
    1544         [ +  - ]:           2 :         ereport(ERROR,
    1545                 :             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    1546                 :             :                  errmsg("cannot set option \"%s\" for enabled subscription",
    1547                 :             :                         option)));
    1548                 :             : 
    1549         [ +  + ]:          12 :     if (slot_needs_update)
    1550                 :             :     {
    1551                 :             :         StringInfoData cmd;
    1552                 :             : 
    1553                 :             :         /*
    1554                 :             :          * A valid slot must be associated with the subscription for us to
    1555                 :             :          * modify any of the slot's properties.
    1556                 :             :          */
    1557         [ -  + ]:           9 :         if (!sub->slotname)
    1558         [ #  # ]:           0 :             ereport(ERROR,
    1559                 :             :                     (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    1560                 :             :                      errmsg("cannot set option \"%s\" for a subscription that does not have a slot name",
    1561                 :             :                             option)));
    1562                 :             : 
    1563                 :             :         /* The changed option of the slot can't be rolled back. */
    1564                 :           9 :         initStringInfo(&cmd);
    1565                 :           9 :         appendStringInfo(&cmd, "ALTER SUBSCRIPTION ... SET (%s)", option);
    1566                 :             : 
    1567                 :           9 :         PreventInTransactionBlock(isTopLevel, cmd.data);
    1568                 :           5 :         pfree(cmd.data);
    1569                 :             :     }
    1570                 :           8 : }
    1571                 :             : 
    1572                 :             : /*
    1573                 :             :  * alter_sub_conflict_log_dest
    1574                 :             :  *
    1575                 :             :  * When the subscription's 'conflict_log_destination' is changed, update the
    1576                 :             :  * conflict log table if required.
    1577                 :             :  *
    1578                 :             :  * If the new destination no longer requires a conflict log table, the existing
    1579                 :             :  * conflict log table associated with the subscription is removed via internal
    1580                 :             :  * dependency cleanup to prevent orphaned relations.
    1581                 :             :  *
    1582                 :             :  * On success, *conflicttablerelid is set to the OID of the conflict log table
    1583                 :             :  * that was created or validated, or to InvalidOid if no table is required.
    1584                 :             :  *
    1585                 :             :  * Returns true if the subscription's conflict log table reference must be
    1586                 :             :  * updated as a result of the destination change; false otherwise.
    1587                 :             :  */
    1588                 :             : static bool
    1589                 :          12 : alter_sub_conflict_log_dest(Subscription *sub, ConflictLogDest oldlogdest,
    1590                 :             :                             ConflictLogDest newlogdest,
    1591                 :             :                             Oid *conflicttablerelid)
    1592                 :             : {
    1593                 :             :     bool        want_table;
    1594                 :             :     bool        has_oldtable;
    1595                 :          12 :     bool        update_relid = false;
    1596                 :          12 :     Oid         relid = InvalidOid;
    1597                 :             : 
    1598   [ +  +  +  + ]:          12 :     want_table = CONFLICTS_LOGGED_TO_TABLE(newlogdest);
    1599   [ +  +  +  + ]:          12 :     has_oldtable = CONFLICTS_LOGGED_TO_TABLE(oldlogdest);
    1600                 :             : 
    1601         [ +  + ]:          12 :     if (has_oldtable)
    1602                 :             :     {
    1603                 :             :         /* There is a conflict log table already. */
    1604         [ +  + ]:           8 :         if (!want_table)
    1605                 :             :         {
    1606                 :           4 :             drop_sub_conflict_log_table(sub->oid, sub->name,
    1607                 :             :                                         sub->conflictlogrelid);
    1608                 :           4 :             update_relid = true;
    1609                 :             :         }
    1610                 :             :     }
    1611                 :             :     else
    1612                 :             :     {
    1613                 :             :         /* There was no previous conflict log table. */
    1614         [ +  - ]:           4 :         if (want_table)
    1615                 :             :         {
    1616                 :             :             ObjectAddress cltaddr;
    1617                 :             :             ObjectAddress subobj;
    1618                 :             : 
    1619                 :           4 :             relid = create_conflict_log_table(sub->oid, sub->name, sub->owner);
    1620                 :           4 :             update_relid = true;
    1621                 :             : 
    1622                 :             :             /*
    1623                 :             :              * Establish an internal dependency between the conflict log table
    1624                 :             :              * and the subscription.  For details refer comments in
    1625                 :             :              * CreateSubscription function.
    1626                 :             :              */
    1627                 :           4 :             ObjectAddressSet(cltaddr, RelationRelationId, relid);
    1628                 :           4 :             ObjectAddressSet(subobj, SubscriptionRelationId, sub->oid);
    1629                 :           4 :             recordDependencyOn(&cltaddr, &subobj, DEPENDENCY_INTERNAL);
    1630                 :             :         }
    1631                 :             :     }
    1632                 :             : 
    1633                 :          12 :     *conflicttablerelid = relid;
    1634                 :          12 :     return update_relid;
    1635                 :             : }
    1636                 :             : 
    1637                 :             : /*
    1638                 :             :  * Alter the existing subscription.
    1639                 :             :  */
    1640                 :             : ObjectAddress
    1641                 :         442 : AlterSubscription(ParseState *pstate, AlterSubscriptionStmt *stmt,
    1642                 :             :                   bool isTopLevel)
    1643                 :             : {
    1644                 :             :     Relation    rel;
    1645                 :             :     ObjectAddress myself;
    1646                 :             :     bool        nulls[Natts_pg_subscription];
    1647                 :             :     bool        replaces[Natts_pg_subscription];
    1648                 :             :     Datum       values[Natts_pg_subscription];
    1649                 :             :     HeapTuple   tup;
    1650                 :             :     Oid         subid;
    1651                 :         442 :     bool        orig_conninfo_needed = false;
    1652                 :         442 :     bool        update_tuple = false;
    1653                 :         442 :     bool        update_failover = false;
    1654                 :         442 :     bool        update_two_phase = false;
    1655                 :         442 :     bool        check_pub_rdt = false;
    1656                 :             :     bool        retain_dead_tuples;
    1657                 :             :     int         max_retention;
    1658                 :             :     bool        retention_active;
    1659                 :         442 :     char       *new_conninfo = NULL;
    1660                 :         442 :     char       *orig_conninfo = NULL;
    1661                 :             :     char       *origin;
    1662                 :             :     Subscription *sub;
    1663                 :             :     Form_pg_subscription form;
    1664                 :             :     uint32      supported_opts;
    1665                 :         442 :     SubOpts     opts = {0};
    1666                 :             : 
    1667                 :         442 :     rel = table_open(SubscriptionRelationId, RowExclusiveLock);
    1668                 :             : 
    1669                 :             :     /* Fetch the existing tuple. */
    1670                 :         442 :     tup = SearchSysCacheCopy2(SUBSCRIPTIONNAME, ObjectIdGetDatum(MyDatabaseId),
    1671                 :             :                               CStringGetDatum(stmt->subname));
    1672                 :             : 
    1673         [ +  + ]:         442 :     if (!HeapTupleIsValid(tup))
    1674         [ +  - ]:           4 :         ereport(ERROR,
    1675                 :             :                 (errcode(ERRCODE_UNDEFINED_OBJECT),
    1676                 :             :                  errmsg("subscription \"%s\" does not exist",
    1677                 :             :                         stmt->subname)));
    1678                 :             : 
    1679                 :         438 :     form = (Form_pg_subscription) GETSTRUCT(tup);
    1680                 :         438 :     subid = form->oid;
    1681                 :             : 
    1682                 :             :     /* must be owner */
    1683         [ -  + ]:         438 :     if (!object_ownercheck(SubscriptionRelationId, subid, GetUserId()))
    1684                 :           0 :         aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_SUBSCRIPTION,
    1685                 :           0 :                        stmt->subname);
    1686                 :             : 
    1687                 :             :     /* parse and check options */
    1688   [ +  +  +  +  :         438 :     switch (stmt->kind)
                +  +  + ]
    1689                 :             :     {
    1690                 :         209 :         case ALTER_SUBSCRIPTION_OPTIONS:
    1691                 :         209 :             supported_opts = (SUBOPT_SLOT_NAME |
    1692                 :             :                               SUBOPT_SYNCHRONOUS_COMMIT | SUBOPT_BINARY |
    1693                 :             :                               SUBOPT_STREAMING | SUBOPT_TWOPHASE_COMMIT |
    1694                 :             :                               SUBOPT_DISABLE_ON_ERR |
    1695                 :             :                               SUBOPT_PASSWORD_REQUIRED |
    1696                 :             :                               SUBOPT_RUN_AS_OWNER | SUBOPT_FAILOVER |
    1697                 :             :                               SUBOPT_RETAIN_DEAD_TUPLES |
    1698                 :             :                               SUBOPT_MAX_RETENTION_DURATION |
    1699                 :             :                               SUBOPT_WAL_RECEIVER_TIMEOUT |
    1700                 :             :                               SUBOPT_ORIGIN |
    1701                 :             :                               SUBOPT_CONFLICT_LOG_DEST);
    1702                 :         209 :             break;
    1703                 :             : 
    1704                 :          87 :         case ALTER_SUBSCRIPTION_ENABLED:
    1705                 :          87 :             supported_opts = SUBOPT_ENABLED;
    1706                 :          87 :             break;
    1707                 :             : 
    1708                 :          23 :         case ALTER_SUBSCRIPTION_SET_PUBLICATION:
    1709                 :          23 :             supported_opts = SUBOPT_COPY_DATA | SUBOPT_REFRESH;
    1710                 :          23 :             break;
    1711                 :             : 
    1712                 :          35 :         case ALTER_SUBSCRIPTION_ADD_PUBLICATION:
    1713                 :             :         case ALTER_SUBSCRIPTION_DROP_PUBLICATION:
    1714                 :          35 :             supported_opts = SUBOPT_REFRESH | SUBOPT_COPY_DATA;
    1715                 :          35 :             break;
    1716                 :             : 
    1717                 :          41 :         case ALTER_SUBSCRIPTION_REFRESH_PUBLICATION:
    1718                 :          41 :             supported_opts = SUBOPT_COPY_DATA;
    1719                 :          41 :             break;
    1720                 :             : 
    1721                 :          15 :         case ALTER_SUBSCRIPTION_SKIP:
    1722                 :          15 :             supported_opts = SUBOPT_LSN;
    1723                 :          15 :             break;
    1724                 :             : 
    1725                 :          28 :         default:
    1726                 :          28 :             supported_opts = 0;
    1727                 :          28 :             break;
    1728                 :             :     }
    1729                 :             : 
    1730         [ +  + ]:         438 :     if (supported_opts > 0)
    1731                 :         410 :         parse_subscription_options(pstate, stmt->options, supported_opts, &opts);
    1732                 :             : 
    1733                 :         414 :     sub = GetSubscription(subid, false);
    1734                 :             : 
    1735                 :             :     /*
    1736                 :             :      * Determine in advance whether we need the original conninfo or not, so
    1737                 :             :      * that errors are generated consistently in cases where we do need it;
    1738                 :             :      * and not generated at all if we don't.
    1739                 :             :      */
    1740                 :             : 
    1741                 :             :     /* conninfo needed when refreshing */
    1742   [ +  +  +  + ]:         414 :     switch (stmt->kind)
    1743                 :             :     {
    1744                 :          46 :         case ALTER_SUBSCRIPTION_REFRESH_PUBLICATION:
    1745                 :             :         case ALTER_SUBSCRIPTION_REFRESH_SEQUENCES:
    1746                 :          46 :             orig_conninfo_needed = true;
    1747                 :          46 :             break;
    1748                 :             : 
    1749                 :          58 :         case ALTER_SUBSCRIPTION_SET_PUBLICATION:
    1750                 :             :         case ALTER_SUBSCRIPTION_ADD_PUBLICATION:
    1751                 :             :         case ALTER_SUBSCRIPTION_DROP_PUBLICATION:
    1752                 :             :             /* opts.refresh defaults to true when the option is supported */
    1753                 :          58 :             orig_conninfo_needed = opts.refresh;
    1754                 :          58 :             break;
    1755                 :             : 
    1756                 :         189 :         case ALTER_SUBSCRIPTION_OPTIONS:
    1757                 :             :             {
    1758         [ +  + ]:         189 :                 if (sub->slotname)
    1759                 :             :                 {
    1760         [ +  + ]:         185 :                     if (IsSet(opts.specified_opts, SUBOPT_FAILOVER))
    1761                 :           9 :                         orig_conninfo_needed = true;
    1762         [ +  + ]:         185 :                     if (IsSet(opts.specified_opts, SUBOPT_TWOPHASE_COMMIT) &&
    1763         [ +  + ]:           3 :                         !opts.twophase)
    1764                 :           1 :                         orig_conninfo_needed = true;
    1765                 :             :                 }
    1766                 :             : 
    1767         [ +  + ]:         189 :                 if (IsSet(opts.specified_opts, SUBOPT_RETAIN_DEAD_TUPLES) &&
    1768         [ +  - ]:           2 :                     opts.retaindeadtuples)
    1769                 :           2 :                     orig_conninfo_needed = true;
    1770                 :             : 
    1771         [ +  + ]:         189 :                 if (IsSet(opts.specified_opts, SUBOPT_ORIGIN))
    1772                 :             :                 {
    1773                 :             :                     bool        rdt;
    1774                 :             : 
    1775                 :          12 :                     rdt = IsSet(opts.specified_opts, SUBOPT_RETAIN_DEAD_TUPLES) ?
    1776         [ -  + ]:           6 :                         opts.retaindeadtuples : sub->retaindeadtuples;
    1777                 :             : 
    1778   [ +  +  +  + ]:           6 :                     if (rdt && pg_strcasecmp(opts.origin, LOGICALREP_ORIGIN_ANY) == 0)
    1779                 :           1 :                         orig_conninfo_needed = true;
    1780                 :             :                 }
    1781                 :             :             }
    1782                 :         189 :             break;
    1783                 :             : 
    1784                 :         121 :         default:
    1785                 :         121 :             break;
    1786                 :             :     }
    1787                 :             : 
    1788         [ +  + ]:         414 :     if (orig_conninfo_needed)
    1789                 :          77 :         orig_conninfo = SubscriptionConninfo(sub);
    1790                 :             : 
    1791                 :         410 :     retain_dead_tuples = sub->retaindeadtuples;
    1792                 :         410 :     origin = sub->origin;
    1793                 :         410 :     max_retention = sub->maxretention;
    1794                 :         410 :     retention_active = sub->retentionactive;
    1795                 :             : 
    1796                 :             :     /*
    1797                 :             :      * Don't allow non-superuser modification of a subscription with
    1798                 :             :      * password_required=false.
    1799                 :             :      */
    1800   [ +  +  -  + ]:         410 :     if (!sub->passwordrequired && !superuser())
    1801         [ #  # ]:           0 :         ereport(ERROR,
    1802                 :             :                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
    1803                 :             :                  errmsg("password_required=false is superuser-only"),
    1804                 :             :                  errhint("Subscriptions with the password_required option set to false may only be created or modified by the superuser.")));
    1805                 :             : 
    1806                 :             :     /* Lock the subscription so nobody else can do anything with it. */
    1807                 :         410 :     LockSharedObject(SubscriptionRelationId, subid, 0, AccessExclusiveLock);
    1808                 :             : 
    1809                 :             :     /* Form a new tuple. */
    1810                 :         410 :     memset(values, 0, sizeof(values));
    1811                 :         410 :     memset(nulls, false, sizeof(nulls));
    1812                 :         410 :     memset(replaces, false, sizeof(replaces));
    1813                 :             : 
    1814                 :         410 :     ObjectAddressSet(myself, SubscriptionRelationId, subid);
    1815                 :             : 
    1816   [ +  +  +  +  :         410 :     switch (stmt->kind)
          +  +  +  +  +  
                      - ]
    1817                 :             :     {
    1818                 :         189 :         case ALTER_SUBSCRIPTION_OPTIONS:
    1819                 :             :             {
    1820         [ +  + ]:         189 :                 if (IsSet(opts.specified_opts, SUBOPT_SLOT_NAME))
    1821                 :             :                 {
    1822                 :             :                     /*
    1823                 :             :                      * The subscription must be disabled to allow slot_name as
    1824                 :             :                      * 'none', otherwise, the apply worker will repeatedly try
    1825                 :             :                      * to stream the data using that slot_name which neither
    1826                 :             :                      * exists on the publisher nor the user will be allowed to
    1827                 :             :                      * create it.
    1828                 :             :                      */
    1829   [ -  +  -  - ]:          72 :                     if (sub->enabled && !opts.slot_name)
    1830         [ #  # ]:           0 :                         ereport(ERROR,
    1831                 :             :                                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    1832                 :             :                                  errmsg("cannot set %s for enabled subscription",
    1833                 :             :                                         "slot_name = NONE")));
    1834                 :             : 
    1835         [ +  + ]:          72 :                     if (opts.slot_name)
    1836                 :           4 :                         values[Anum_pg_subscription_subslotname - 1] =
    1837                 :           4 :                             DirectFunctionCall1(namein, CStringGetDatum(opts.slot_name));
    1838                 :             :                     else
    1839                 :          68 :                         nulls[Anum_pg_subscription_subslotname - 1] = true;
    1840                 :          72 :                     replaces[Anum_pg_subscription_subslotname - 1] = true;
    1841                 :             :                 }
    1842                 :             : 
    1843         [ +  + ]:         189 :                 if (opts.synchronous_commit)
    1844                 :             :                 {
    1845                 :          12 :                     values[Anum_pg_subscription_subsynccommit - 1] =
    1846                 :          12 :                         CStringGetTextDatum(opts.synchronous_commit);
    1847                 :          12 :                     replaces[Anum_pg_subscription_subsynccommit - 1] = true;
    1848                 :             :                 }
    1849                 :             : 
    1850         [ +  + ]:         189 :                 if (IsSet(opts.specified_opts, SUBOPT_BINARY))
    1851                 :             :                 {
    1852                 :          10 :                     values[Anum_pg_subscription_subbinary - 1] =
    1853                 :          10 :                         BoolGetDatum(opts.binary);
    1854                 :          10 :                     replaces[Anum_pg_subscription_subbinary - 1] = true;
    1855                 :             :                 }
    1856                 :             : 
    1857         [ +  + ]:         189 :                 if (IsSet(opts.specified_opts, SUBOPT_STREAMING))
    1858                 :             :                 {
    1859                 :          18 :                     values[Anum_pg_subscription_substream - 1] =
    1860                 :          18 :                         CharGetDatum(opts.streaming);
    1861                 :          18 :                     replaces[Anum_pg_subscription_substream - 1] = true;
    1862                 :             :                 }
    1863                 :             : 
    1864         [ +  + ]:         189 :                 if (IsSet(opts.specified_opts, SUBOPT_DISABLE_ON_ERR))
    1865                 :             :                 {
    1866                 :             :                     values[Anum_pg_subscription_subdisableonerr - 1]
    1867                 :          12 :                         = BoolGetDatum(opts.disableonerr);
    1868                 :             :                     replaces[Anum_pg_subscription_subdisableonerr - 1]
    1869                 :          12 :                         = true;
    1870                 :             :                 }
    1871                 :             : 
    1872         [ +  + ]:         189 :                 if (IsSet(opts.specified_opts, SUBOPT_PASSWORD_REQUIRED))
    1873                 :             :                 {
    1874                 :             :                     /* Non-superuser may not disable password_required. */
    1875   [ +  +  -  + ]:           8 :                     if (!opts.passwordrequired && !superuser())
    1876         [ #  # ]:           0 :                         ereport(ERROR,
    1877                 :             :                                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
    1878                 :             :                                  errmsg("password_required=false is superuser-only"),
    1879                 :             :                                  errhint("Subscriptions with the password_required option set to false may only be created or modified by the superuser.")));
    1880                 :             : 
    1881                 :             :                     values[Anum_pg_subscription_subpasswordrequired - 1]
    1882                 :           8 :                         = BoolGetDatum(opts.passwordrequired);
    1883                 :             :                     replaces[Anum_pg_subscription_subpasswordrequired - 1]
    1884                 :           8 :                         = true;
    1885                 :             :                 }
    1886                 :             : 
    1887         [ +  + ]:         189 :                 if (IsSet(opts.specified_opts, SUBOPT_RUN_AS_OWNER))
    1888                 :             :                 {
    1889                 :           9 :                     values[Anum_pg_subscription_subrunasowner - 1] =
    1890                 :           9 :                         BoolGetDatum(opts.runasowner);
    1891                 :           9 :                     replaces[Anum_pg_subscription_subrunasowner - 1] = true;
    1892                 :             :                 }
    1893                 :             : 
    1894         [ +  + ]:         189 :                 if (IsSet(opts.specified_opts, SUBOPT_TWOPHASE_COMMIT))
    1895                 :             :                 {
    1896                 :             :                     /*
    1897                 :             :                      * We need to update both the slot and the subscription
    1898                 :             :                      * for the two_phase option. We can enable the two_phase
    1899                 :             :                      * option for a slot only once the initial data
    1900                 :             :                      * synchronization is done. This is to avoid missing some
    1901                 :             :                      * data as explained in comments atop worker.c.
    1902                 :             :                      */
    1903                 :           3 :                     update_two_phase = !opts.twophase;
    1904                 :             : 
    1905                 :           3 :                     CheckAlterSubOption(sub, "two_phase", update_two_phase,
    1906                 :             :                                         isTopLevel);
    1907                 :             : 
    1908                 :             :                     /*
    1909                 :             :                      * Modifying the two_phase slot option requires a slot
    1910                 :             :                      * lookup by slot name, so changing the slot name at the
    1911                 :             :                      * same time is not allowed.
    1912                 :             :                      */
    1913         [ +  + ]:           3 :                     if (update_two_phase &&
    1914         [ -  + ]:           1 :                         IsSet(opts.specified_opts, SUBOPT_SLOT_NAME))
    1915         [ #  # ]:           0 :                         ereport(ERROR,
    1916                 :             :                                 (errcode(ERRCODE_SYNTAX_ERROR),
    1917                 :             :                                  errmsg("\"slot_name\" and \"two_phase\" cannot be altered at the same time")));
    1918                 :             : 
    1919                 :             :                     /*
    1920                 :             :                      * Note that workers may still survive even if the
    1921                 :             :                      * subscription has been disabled.
    1922                 :             :                      *
    1923                 :             :                      * Ensure workers have already been exited to avoid
    1924                 :             :                      * getting prepared transactions while we are disabling
    1925                 :             :                      * the two_phase option. Otherwise, the changes of an
    1926                 :             :                      * already prepared transaction can be replicated again
    1927                 :             :                      * along with its corresponding commit, leading to
    1928                 :             :                      * duplicate data or errors.
    1929                 :             :                      */
    1930         [ -  + ]:           3 :                     if (logicalrep_workers_find(subid, true, true))
    1931         [ #  # ]:           0 :                         ereport(ERROR,
    1932                 :             :                                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    1933                 :             :                                  errmsg("cannot alter \"two_phase\" when logical replication worker is still running"),
    1934                 :             :                                  errhint("Try again after some time.")));
    1935                 :             : 
    1936                 :             :                     /*
    1937                 :             :                      * two_phase cannot be disabled if there are any
    1938                 :             :                      * uncommitted prepared transactions present otherwise it
    1939                 :             :                      * can lead to duplicate data or errors as explained in
    1940                 :             :                      * the comment above.
    1941                 :             :                      */
    1942         [ +  + ]:           3 :                     if (update_two_phase &&
    1943         [ +  - ]:           1 :                         sub->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED &&
    1944         [ -  + ]:           1 :                         LookupGXactBySubid(subid))
    1945         [ #  # ]:           0 :                         ereport(ERROR,
    1946                 :             :                                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    1947                 :             :                                  errmsg("cannot disable \"two_phase\" when prepared transactions exist"),
    1948                 :             :                                  errhint("Resolve these transactions and try again.")));
    1949                 :             : 
    1950                 :             :                     /* Change system catalog accordingly */
    1951                 :           3 :                     values[Anum_pg_subscription_subtwophasestate - 1] =
    1952         [ +  + ]:           3 :                         CharGetDatum(opts.twophase ?
    1953                 :             :                                      LOGICALREP_TWOPHASE_STATE_PENDING :
    1954                 :             :                                      LOGICALREP_TWOPHASE_STATE_DISABLED);
    1955                 :           3 :                     replaces[Anum_pg_subscription_subtwophasestate - 1] = true;
    1956                 :             :                 }
    1957                 :             : 
    1958         [ +  + ]:         189 :                 if (IsSet(opts.specified_opts, SUBOPT_FAILOVER))
    1959                 :             :                 {
    1960                 :             :                     /*
    1961                 :             :                      * Similar to the two_phase case above, we need to update
    1962                 :             :                      * the failover option for both the slot and the
    1963                 :             :                      * subscription.
    1964                 :             :                      */
    1965                 :           9 :                     update_failover = true;
    1966                 :             : 
    1967                 :           9 :                     CheckAlterSubOption(sub, "failover", update_failover,
    1968                 :             :                                         isTopLevel);
    1969                 :             : 
    1970                 :           4 :                     values[Anum_pg_subscription_subfailover - 1] =
    1971                 :           4 :                         BoolGetDatum(opts.failover);
    1972                 :           4 :                     replaces[Anum_pg_subscription_subfailover - 1] = true;
    1973                 :             :                 }
    1974                 :             : 
    1975         [ +  + ]:         184 :                 if (IsSet(opts.specified_opts, SUBOPT_RETAIN_DEAD_TUPLES))
    1976                 :             :                 {
    1977                 :           2 :                     values[Anum_pg_subscription_subretaindeadtuples - 1] =
    1978                 :           2 :                         BoolGetDatum(opts.retaindeadtuples);
    1979                 :           2 :                     replaces[Anum_pg_subscription_subretaindeadtuples - 1] = true;
    1980                 :             : 
    1981                 :             :                     /*
    1982                 :             :                      * Update the retention status only if there's a change in
    1983                 :             :                      * the retain_dead_tuples option value.
    1984                 :             :                      *
    1985                 :             :                      * Automatically marking retention as active when
    1986                 :             :                      * retain_dead_tuples is enabled may not always be ideal,
    1987                 :             :                      * especially if retention was previously stopped and the
    1988                 :             :                      * user toggles retain_dead_tuples without adjusting the
    1989                 :             :                      * publisher workload. However, this behavior provides a
    1990                 :             :                      * convenient way for users to manually refresh the
    1991                 :             :                      * retention status. Since retention will be stopped again
    1992                 :             :                      * unless the publisher workload is reduced, this approach
    1993                 :             :                      * is acceptable for now.
    1994                 :             :                      */
    1995         [ +  - ]:           2 :                     if (opts.retaindeadtuples != sub->retaindeadtuples)
    1996                 :             :                     {
    1997                 :           2 :                         values[Anum_pg_subscription_subretentionactive - 1] =
    1998                 :           2 :                             BoolGetDatum(opts.retaindeadtuples);
    1999                 :           2 :                         replaces[Anum_pg_subscription_subretentionactive - 1] = true;
    2000                 :             : 
    2001                 :           2 :                         retention_active = opts.retaindeadtuples;
    2002                 :             :                     }
    2003                 :             : 
    2004                 :           2 :                     CheckAlterSubOption(sub, "retain_dead_tuples", false, isTopLevel);
    2005                 :             : 
    2006                 :             :                     /*
    2007                 :             :                      * Workers may continue running even after the
    2008                 :             :                      * subscription has been disabled.
    2009                 :             :                      *
    2010                 :             :                      * To prevent race conditions (as described in
    2011                 :             :                      * CheckAlterSubOption()), ensure that all worker
    2012                 :             :                      * processes have already exited before proceeding.
    2013                 :             :                      */
    2014         [ -  + ]:           1 :                     if (logicalrep_workers_find(subid, true, true))
    2015         [ #  # ]:           0 :                         ereport(ERROR,
    2016                 :             :                                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    2017                 :             :                                  errmsg("cannot alter retain_dead_tuples when logical replication worker is still running"),
    2018                 :             :                                  errhint("Try again after some time.")));
    2019                 :             : 
    2020                 :             :                     /*
    2021                 :             :                      * Notify the launcher to manage the replication slot for
    2022                 :             :                      * conflict detection. This ensures that replication slot
    2023                 :             :                      * is efficiently handled (created, updated, or dropped)
    2024                 :             :                      * in response to any configuration changes.
    2025                 :             :                      */
    2026                 :           1 :                     ApplyLauncherWakeupAtCommit();
    2027                 :             : 
    2028                 :           1 :                     check_pub_rdt = opts.retaindeadtuples;
    2029                 :           1 :                     retain_dead_tuples = opts.retaindeadtuples;
    2030                 :             :                 }
    2031                 :             : 
    2032         [ +  + ]:         183 :                 if (IsSet(opts.specified_opts, SUBOPT_MAX_RETENTION_DURATION))
    2033                 :             :                 {
    2034                 :           6 :                     values[Anum_pg_subscription_submaxretention - 1] =
    2035                 :           6 :                         Int32GetDatum(opts.maxretention);
    2036                 :           6 :                     replaces[Anum_pg_subscription_submaxretention - 1] = true;
    2037                 :             : 
    2038                 :           6 :                     max_retention = opts.maxretention;
    2039                 :             :                 }
    2040                 :             : 
    2041                 :             :                 /*
    2042                 :             :                  * Ensure that system configuration parameters are set
    2043                 :             :                  * appropriately to support retain_dead_tuples and
    2044                 :             :                  * max_retention_duration.
    2045                 :             :                  */
    2046         [ +  + ]:         183 :                 if (IsSet(opts.specified_opts, SUBOPT_RETAIN_DEAD_TUPLES) ||
    2047         [ +  + ]:         182 :                     IsSet(opts.specified_opts, SUBOPT_MAX_RETENTION_DURATION))
    2048                 :           7 :                     CheckSubDeadTupleRetention(true, !sub->enabled, NOTICE,
    2049                 :             :                                                retain_dead_tuples,
    2050                 :             :                                                retention_active,
    2051                 :           7 :                                                (max_retention > 0));
    2052                 :             : 
    2053         [ +  + ]:         183 :                 if (IsSet(opts.specified_opts, SUBOPT_ORIGIN))
    2054                 :             :                 {
    2055                 :           6 :                     values[Anum_pg_subscription_suborigin - 1] =
    2056                 :           6 :                         CStringGetTextDatum(opts.origin);
    2057                 :           6 :                     replaces[Anum_pg_subscription_suborigin - 1] = true;
    2058                 :             : 
    2059                 :             :                     /*
    2060                 :             :                      * Check if changes from different origins may be received
    2061                 :             :                      * from the publisher when the origin is changed to ANY
    2062                 :             :                      * and retain_dead_tuples is enabled. Use |= so that we
    2063                 :             :                      * don't clear the flag already set when
    2064                 :             :                      * retain_dead_tuples was changed in the same command.
    2065                 :             :                      */
    2066         [ +  + ]:           8 :                     check_pub_rdt |= retain_dead_tuples &&
    2067         [ +  + ]:           2 :                         pg_strcasecmp(opts.origin, LOGICALREP_ORIGIN_ANY) == 0;
    2068                 :             : 
    2069                 :           6 :                     origin = opts.origin;
    2070                 :             :                 }
    2071                 :             : 
    2072         [ +  + ]:         183 :                 if (IsSet(opts.specified_opts, SUBOPT_WAL_RECEIVER_TIMEOUT))
    2073                 :             :                 {
    2074                 :           8 :                     values[Anum_pg_subscription_subwalrcvtimeout - 1] =
    2075                 :           8 :                         CStringGetTextDatum(opts.wal_receiver_timeout);
    2076                 :           8 :                     replaces[Anum_pg_subscription_subwalrcvtimeout - 1] = true;
    2077                 :             :                 }
    2078                 :             : 
    2079         [ +  + ]:         183 :                 if (IsSet(opts.specified_opts, SUBOPT_CONFLICT_LOG_DEST))
    2080                 :             :                 {
    2081                 :             :                     ConflictLogDest old_dest =
    2082                 :          16 :                         GetConflictLogDest(sub->conflictlogdest);
    2083                 :             : 
    2084         [ +  + ]:          16 :                     if (opts.conflictlogdest != old_dest)
    2085                 :             :                     {
    2086                 :             :                         bool        update_relid;
    2087                 :          12 :                         Oid         relid = InvalidOid;
    2088                 :             : 
    2089                 :          12 :                         values[Anum_pg_subscription_subconflictlogdest - 1] =
    2090                 :          12 :                             CStringGetTextDatum(ConflictLogDestNames[opts.conflictlogdest]);
    2091                 :          12 :                         replaces[Anum_pg_subscription_subconflictlogdest - 1] = true;
    2092                 :             : 
    2093                 :          12 :                         update_relid = alter_sub_conflict_log_dest(sub,
    2094                 :             :                                                                    old_dest,
    2095                 :             :                                                                    opts.conflictlogdest,
    2096                 :             :                                                                    &relid);
    2097         [ +  + ]:          12 :                         if (update_relid)
    2098                 :             :                         {
    2099                 :           8 :                             values[Anum_pg_subscription_subconflictlogrelid - 1] =
    2100                 :           8 :                                 ObjectIdGetDatum(relid);
    2101                 :           8 :                             replaces[Anum_pg_subscription_subconflictlogrelid - 1] =
    2102                 :             :                                 true;
    2103                 :             :                         }
    2104                 :             :                     }
    2105                 :             :                 }
    2106                 :             : 
    2107                 :         183 :                 update_tuple = true;
    2108                 :         183 :                 break;
    2109                 :             :             }
    2110                 :             : 
    2111                 :          87 :         case ALTER_SUBSCRIPTION_ENABLED:
    2112                 :             :             {
    2113                 :             :                 Assert(IsSet(opts.specified_opts, SUBOPT_ENABLED));
    2114                 :             : 
    2115   [ +  +  +  - ]:          87 :                 if (!sub->slotname && opts.enabled)
    2116         [ +  - ]:           4 :                     ereport(ERROR,
    2117                 :             :                             (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    2118                 :             :                              errmsg("cannot enable subscription that does not have a slot name")));
    2119                 :             : 
    2120                 :             :                 /*
    2121                 :             :                  * Check track_commit_timestamp only when enabling the
    2122                 :             :                  * subscription in case it was disabled after creation. See
    2123                 :             :                  * comments atop CheckSubDeadTupleRetention() for details.
    2124                 :             :                  */
    2125                 :          83 :                 CheckSubDeadTupleRetention(opts.enabled, !opts.enabled,
    2126                 :          83 :                                            WARNING, sub->retaindeadtuples,
    2127                 :          83 :                                            sub->retentionactive, false);
    2128                 :             : 
    2129                 :          83 :                 values[Anum_pg_subscription_subenabled - 1] =
    2130                 :          83 :                     BoolGetDatum(opts.enabled);
    2131                 :          83 :                 replaces[Anum_pg_subscription_subenabled - 1] = true;
    2132                 :             : 
    2133         [ +  + ]:          83 :                 if (opts.enabled)
    2134                 :          34 :                     ApplyLauncherWakeupAtCommit();
    2135                 :             : 
    2136                 :          83 :                 update_tuple = true;
    2137                 :          83 :                 break;
    2138                 :             :             }
    2139                 :             : 
    2140                 :           1 :         case ALTER_SUBSCRIPTION_SERVER:
    2141                 :             :             {
    2142                 :             :                 ForeignServer *new_server;
    2143                 :             :                 ObjectAddress referenced;
    2144                 :             :                 AclResult   aclresult;
    2145                 :             : 
    2146                 :             :                 /*
    2147                 :             :                  * Remove what was there before, either another foreign server
    2148                 :             :                  * or a connection string.
    2149                 :             :                  */
    2150         [ -  + ]:           1 :                 if (form->subserver)
    2151                 :             :                 {
    2152                 :           0 :                     deleteDependencyRecordsForSpecific(SubscriptionRelationId, form->oid,
    2153                 :             :                                                        DEPENDENCY_NORMAL,
    2154                 :             :                                                        ForeignServerRelationId, form->subserver);
    2155                 :             :                 }
    2156                 :             :                 else
    2157                 :             :                 {
    2158                 :           1 :                     nulls[Anum_pg_subscription_subconninfo - 1] = true;
    2159                 :           1 :                     replaces[Anum_pg_subscription_subconninfo - 1] = true;
    2160                 :             :                 }
    2161                 :             : 
    2162                 :             :                 /*
    2163                 :             :                  * Check that the subscription owner has USAGE privileges on
    2164                 :             :                  * the server.
    2165                 :             :                  */
    2166                 :           1 :                 new_server = GetForeignServerByName(stmt->servername, false);
    2167                 :           1 :                 aclresult = object_aclcheck(ForeignServerRelationId,
    2168                 :             :                                             new_server->serverid,
    2169                 :             :                                             form->subowner, ACL_USAGE);
    2170         [ -  + ]:           1 :                 if (aclresult != ACLCHECK_OK)
    2171         [ #  # ]:           0 :                     ereport(ERROR,
    2172                 :             :                             errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
    2173                 :             :                             errmsg("subscription owner \"%s\" does not have permission on foreign server \"%s\"",
    2174                 :             :                                    GetUserNameFromId(form->subowner, false),
    2175                 :             :                                    new_server->servername));
    2176                 :             : 
    2177                 :             :                 /* check user mapping */
    2178                 :           1 :                 GetUserMappingExtended(form->subowner, new_server->serverid, WARNING);
    2179                 :             : 
    2180                 :           1 :                 new_conninfo = ForeignServerConnectionString(form->subowner,
    2181                 :             :                                                              new_server);
    2182                 :             : 
    2183                 :             :                 /* Load the library providing us libpq calls. */
    2184                 :           1 :                 load_file("libpqwalreceiver", false);
    2185                 :             :                 /* Check the connection info string. */
    2186   [ -  +  -  - ]:           1 :                 walrcv_check_conninfo(new_conninfo,
    2187                 :             :                                       sub->passwordrequired && !sub->ownersuperuser);
    2188                 :             : 
    2189                 :           1 :                 values[Anum_pg_subscription_subserver - 1] = ObjectIdGetDatum(new_server->serverid);
    2190                 :           1 :                 replaces[Anum_pg_subscription_subserver - 1] = true;
    2191                 :             : 
    2192                 :           1 :                 ObjectAddressSet(referenced, ForeignServerRelationId, new_server->serverid);
    2193                 :           1 :                 recordDependencyOn(&myself, &referenced, DEPENDENCY_NORMAL);
    2194                 :             : 
    2195                 :           1 :                 update_tuple = true;
    2196                 :             :             }
    2197                 :             : 
    2198                 :             :             /*
    2199                 :             :              * Since the remote server configuration might have changed,
    2200                 :             :              * perform a check to ensure it permits enabling
    2201                 :             :              * retain_dead_tuples.
    2202                 :             :              */
    2203                 :           1 :             check_pub_rdt = sub->retaindeadtuples;
    2204                 :           1 :             break;
    2205                 :             : 
    2206                 :          22 :         case ALTER_SUBSCRIPTION_CONNECTION:
    2207                 :             :             /* remove reference to foreign server and dependencies, if present */
    2208         [ +  + ]:          22 :             if (form->subserver)
    2209                 :             :             {
    2210                 :           9 :                 deleteDependencyRecordsForSpecific(SubscriptionRelationId, form->oid,
    2211                 :             :                                                    DEPENDENCY_NORMAL,
    2212                 :             :                                                    ForeignServerRelationId, form->subserver);
    2213                 :             : 
    2214                 :           9 :                 values[Anum_pg_subscription_subserver - 1] = ObjectIdGetDatum(InvalidOid);
    2215                 :           9 :                 replaces[Anum_pg_subscription_subserver - 1] = true;
    2216                 :             :             }
    2217                 :             : 
    2218                 :          22 :             new_conninfo = stmt->conninfo;
    2219                 :             : 
    2220                 :             :             /* Load the library providing us libpq calls. */
    2221                 :          22 :             load_file("libpqwalreceiver", false);
    2222                 :             :             /* Check the connection info string. */
    2223   [ +  +  +  + ]:          22 :             walrcv_check_conninfo(new_conninfo,
    2224                 :             :                                   sub->passwordrequired && !sub->ownersuperuser);
    2225                 :             : 
    2226                 :          18 :             values[Anum_pg_subscription_subconninfo - 1] =
    2227                 :          18 :                 CStringGetTextDatum(stmt->conninfo);
    2228                 :          18 :             replaces[Anum_pg_subscription_subconninfo - 1] = true;
    2229                 :          18 :             update_tuple = true;
    2230                 :             : 
    2231                 :             :             /*
    2232                 :             :              * Since the remote server configuration might have changed,
    2233                 :             :              * perform a check to ensure it permits enabling
    2234                 :             :              * retain_dead_tuples.
    2235                 :             :              */
    2236                 :          18 :             check_pub_rdt = sub->retaindeadtuples;
    2237                 :          18 :             break;
    2238                 :             : 
    2239                 :          23 :         case ALTER_SUBSCRIPTION_SET_PUBLICATION:
    2240                 :             :             {
    2241                 :          23 :                 values[Anum_pg_subscription_subpublications - 1] =
    2242                 :          23 :                     publicationListToArray(stmt->publication);
    2243                 :          23 :                 replaces[Anum_pg_subscription_subpublications - 1] = true;
    2244                 :             : 
    2245                 :          23 :                 update_tuple = true;
    2246                 :             : 
    2247                 :             :                 /* Refresh if user asked us to. */
    2248         [ +  + ]:          23 :                 if (opts.refresh)
    2249                 :             :                 {
    2250         [ -  + ]:          15 :                     if (!sub->enabled)
    2251         [ #  # ]:           0 :                         ereport(ERROR,
    2252                 :             :                                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    2253                 :             :                                  errmsg("ALTER SUBSCRIPTION with refresh is not allowed for disabled subscriptions"),
    2254                 :             :                                  errhint("Use ALTER SUBSCRIPTION ... SET PUBLICATION ... WITH (refresh = false).")));
    2255                 :             : 
    2256                 :             :                     /*
    2257                 :             :                      * See ALTER_SUBSCRIPTION_REFRESH_PUBLICATION for details
    2258                 :             :                      * why this is not allowed.
    2259                 :             :                      */
    2260   [ -  +  -  - ]:          15 :                     if (sub->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED && opts.copy_data)
    2261         [ #  # ]:           0 :                         ereport(ERROR,
    2262                 :             :                                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    2263                 :             :                                  errmsg("ALTER SUBSCRIPTION with refresh and copy_data is not allowed when two_phase is enabled"),
    2264                 :             :                                  errhint("Use ALTER SUBSCRIPTION ... SET PUBLICATION with refresh = false, or with copy_data = false, or use DROP/CREATE SUBSCRIPTION.")));
    2265                 :             : 
    2266                 :          15 :                     PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION with refresh");
    2267                 :             : 
    2268                 :             :                     /* Make sure refresh sees the new list of publications. */
    2269                 :           7 :                     sub->publications = stmt->publication;
    2270                 :             : 
    2271                 :           7 :                     AlterSubscription_refresh(sub, opts.copy_data,
    2272                 :             :                                               stmt->publication,
    2273                 :             :                                               orig_conninfo);
    2274                 :             :                 }
    2275                 :             : 
    2276                 :          15 :                 break;
    2277                 :             :             }
    2278                 :             : 
    2279                 :          35 :         case ALTER_SUBSCRIPTION_ADD_PUBLICATION:
    2280                 :             :         case ALTER_SUBSCRIPTION_DROP_PUBLICATION:
    2281                 :             :             {
    2282                 :             :                 List       *publist;
    2283                 :          35 :                 bool        isadd = stmt->kind == ALTER_SUBSCRIPTION_ADD_PUBLICATION;
    2284                 :             : 
    2285                 :          35 :                 publist = merge_publications(sub->publications, stmt->publication, isadd, stmt->subname);
    2286                 :          11 :                 values[Anum_pg_subscription_subpublications - 1] =
    2287                 :          11 :                     publicationListToArray(publist);
    2288                 :          11 :                 replaces[Anum_pg_subscription_subpublications - 1] = true;
    2289                 :             : 
    2290                 :          11 :                 update_tuple = true;
    2291                 :             : 
    2292                 :             :                 /* Refresh if user asked us to. */
    2293         [ +  + ]:          11 :                 if (opts.refresh)
    2294                 :             :                 {
    2295                 :             :                     /* We only need to validate user specified publications. */
    2296         [ +  + ]:           3 :                     List       *validate_publications = (isadd) ? stmt->publication : NULL;
    2297                 :             : 
    2298         [ -  + ]:           3 :                     if (!sub->enabled)
    2299   [ #  #  #  # ]:           0 :                         ereport(ERROR,
    2300                 :             :                                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    2301                 :             :                                  errmsg("ALTER SUBSCRIPTION with refresh is not allowed for disabled subscriptions"),
    2302                 :             :                         /* translator: %s is an SQL ALTER command */
    2303                 :             :                                  errhint("Use %s instead.",
    2304                 :             :                                          isadd ?
    2305                 :             :                                          "ALTER SUBSCRIPTION ... ADD PUBLICATION ... WITH (refresh = false)" :
    2306                 :             :                                          "ALTER SUBSCRIPTION ... DROP PUBLICATION ... WITH (refresh = false)")));
    2307                 :             : 
    2308                 :             :                     /*
    2309                 :             :                      * See ALTER_SUBSCRIPTION_REFRESH_PUBLICATION for details
    2310                 :             :                      * why this is not allowed.
    2311                 :             :                      */
    2312   [ -  +  -  - ]:           3 :                     if (sub->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED && opts.copy_data)
    2313   [ #  #  #  # ]:           0 :                         ereport(ERROR,
    2314                 :             :                                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    2315                 :             :                                  errmsg("ALTER SUBSCRIPTION with refresh and copy_data is not allowed when two_phase is enabled"),
    2316                 :             :                         /* translator: %s is an SQL ALTER command */
    2317                 :             :                                  errhint("Use %s with refresh = false, or with copy_data = false, or use DROP/CREATE SUBSCRIPTION.",
    2318                 :             :                                          isadd ?
    2319                 :             :                                          "ALTER SUBSCRIPTION ... ADD PUBLICATION" :
    2320                 :             :                                          "ALTER SUBSCRIPTION ... DROP PUBLICATION")));
    2321                 :             : 
    2322                 :           3 :                     PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION with refresh");
    2323                 :             : 
    2324                 :             :                     /* Refresh the new list of publications. */
    2325                 :           3 :                     sub->publications = publist;
    2326                 :             : 
    2327                 :           3 :                     AlterSubscription_refresh(sub, opts.copy_data,
    2328                 :             :                                               validate_publications,
    2329                 :             :                                               orig_conninfo);
    2330                 :             :                 }
    2331                 :             : 
    2332                 :          11 :                 break;
    2333                 :             :             }
    2334                 :             : 
    2335                 :          37 :         case ALTER_SUBSCRIPTION_REFRESH_PUBLICATION:
    2336                 :             :             {
    2337         [ +  + ]:          37 :                 if (!sub->enabled)
    2338         [ +  - ]:           4 :                     ereport(ERROR,
    2339                 :             :                             (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    2340                 :             :                              errmsg("%s is not allowed for disabled subscriptions",
    2341                 :             :                                     "ALTER SUBSCRIPTION ... REFRESH PUBLICATION")));
    2342                 :             : 
    2343                 :             :                 /*
    2344                 :             :                  * The subscription option "two_phase" requires that
    2345                 :             :                  * replication has passed the initial table synchronization
    2346                 :             :                  * phase before the two_phase becomes properly enabled.
    2347                 :             :                  *
    2348                 :             :                  * But, having reached this two-phase commit "enabled" state
    2349                 :             :                  * we must not allow any subsequent table initialization to
    2350                 :             :                  * occur. So the ALTER SUBSCRIPTION ... REFRESH PUBLICATION is
    2351                 :             :                  * disallowed when the user had requested two_phase = on mode.
    2352                 :             :                  *
    2353                 :             :                  * The exception to this restriction is when copy_data =
    2354                 :             :                  * false, because when copy_data is false the tablesync will
    2355                 :             :                  * start already in READY state and will exit directly without
    2356                 :             :                  * doing anything.
    2357                 :             :                  *
    2358                 :             :                  * For more details see comments atop worker.c.
    2359                 :             :                  */
    2360   [ -  +  -  - ]:          33 :                 if (sub->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED && opts.copy_data)
    2361         [ #  # ]:           0 :                     ereport(ERROR,
    2362                 :             :                             (errcode(ERRCODE_SYNTAX_ERROR),
    2363                 :             :                              errmsg("ALTER SUBSCRIPTION ... REFRESH PUBLICATION with copy_data is not allowed when two_phase is enabled"),
    2364                 :             :                              errhint("Use ALTER SUBSCRIPTION ... REFRESH PUBLICATION with copy_data = false, or use DROP/CREATE SUBSCRIPTION.")));
    2365                 :             : 
    2366                 :          33 :                 PreventInTransactionBlock(isTopLevel, "ALTER SUBSCRIPTION ... REFRESH PUBLICATION");
    2367                 :             : 
    2368                 :          29 :                 AlterSubscription_refresh(sub, opts.copy_data, NULL,
    2369                 :             :                                           orig_conninfo);
    2370                 :             : 
    2371                 :          28 :                 break;
    2372                 :             :             }
    2373                 :             : 
    2374                 :           5 :         case ALTER_SUBSCRIPTION_REFRESH_SEQUENCES:
    2375                 :             :             {
    2376         [ -  + ]:           5 :                 if (!sub->enabled)
    2377         [ #  # ]:           0 :                     ereport(ERROR,
    2378                 :             :                             errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    2379                 :             :                             errmsg("%s is not allowed for disabled subscriptions",
    2380                 :             :                                    "ALTER SUBSCRIPTION ... REFRESH SEQUENCES"));
    2381                 :             : 
    2382                 :           5 :                 AlterSubscription_refresh_seq(sub, orig_conninfo);
    2383                 :             : 
    2384                 :           5 :                 break;
    2385                 :             :             }
    2386                 :             : 
    2387                 :          11 :         case ALTER_SUBSCRIPTION_SKIP:
    2388                 :             :             {
    2389                 :             :                 /* ALTER SUBSCRIPTION ... SKIP supports only LSN option */
    2390                 :             :                 Assert(IsSet(opts.specified_opts, SUBOPT_LSN));
    2391                 :             : 
    2392                 :             :                 /*
    2393                 :             :                  * If the user sets subskiplsn, we do a sanity check to make
    2394                 :             :                  * sure that the specified LSN is a probable value.
    2395                 :             :                  */
    2396         [ +  + ]:          11 :                 if (XLogRecPtrIsValid(opts.lsn))
    2397                 :             :                 {
    2398                 :             :                     ReplOriginId originid;
    2399                 :             :                     char        originname[NAMEDATALEN];
    2400                 :             :                     XLogRecPtr  remote_lsn;
    2401                 :             : 
    2402                 :           7 :                     ReplicationOriginNameForLogicalRep(subid, InvalidOid,
    2403                 :             :                                                        originname, sizeof(originname));
    2404                 :           7 :                     originid = replorigin_by_name(originname, false);
    2405                 :           7 :                     remote_lsn = replorigin_get_progress(originid, false);
    2406                 :             : 
    2407                 :             :                     /* Check the given LSN is at least a future LSN */
    2408   [ +  +  -  + ]:           7 :                     if (XLogRecPtrIsValid(remote_lsn) && opts.lsn < remote_lsn)
    2409         [ #  # ]:           0 :                         ereport(ERROR,
    2410                 :             :                                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    2411                 :             :                                  errmsg("skip WAL location (LSN %X/%08X) must be greater than origin LSN %X/%08X",
    2412                 :             :                                         LSN_FORMAT_ARGS(opts.lsn),
    2413                 :             :                                         LSN_FORMAT_ARGS(remote_lsn))));
    2414                 :             :                 }
    2415                 :             : 
    2416                 :          11 :                 values[Anum_pg_subscription_subskiplsn - 1] = LSNGetDatum(opts.lsn);
    2417                 :          11 :                 replaces[Anum_pg_subscription_subskiplsn - 1] = true;
    2418                 :             : 
    2419                 :          11 :                 update_tuple = true;
    2420                 :          11 :                 break;
    2421                 :             :             }
    2422                 :             : 
    2423                 :           0 :         default:
    2424         [ #  # ]:           0 :             elog(ERROR, "unrecognized ALTER SUBSCRIPTION kind %d",
    2425                 :             :                  stmt->kind);
    2426                 :             :     }
    2427                 :             : 
    2428                 :             :     /* Update the catalog if needed. */
    2429         [ +  + ]:         355 :     if (update_tuple)
    2430                 :             :     {
    2431                 :         322 :         tup = heap_modify_tuple(tup, RelationGetDescr(rel), values, nulls,
    2432                 :             :                                 replaces);
    2433                 :             : 
    2434                 :         322 :         CatalogTupleUpdate(rel, &tup->t_self, tup);
    2435                 :             : 
    2436                 :         322 :         heap_freetuple(tup);
    2437                 :             :     }
    2438                 :             : 
    2439                 :             :     /*
    2440                 :             :      * Try to acquire the connection necessary either for modifying the slot
    2441                 :             :      * or for checking if the remote server permits enabling
    2442                 :             :      * retain_dead_tuples.
    2443                 :             :      *
    2444                 :             :      * This has to be at the end because otherwise if there is an error while
    2445                 :             :      * doing the database operations we won't be able to rollback altered
    2446                 :             :      * slot.
    2447                 :             :      */
    2448   [ +  +  +  +  :         355 :     if (update_failover || update_two_phase || check_pub_rdt)
                   +  + ]
    2449                 :             :     {
    2450                 :             :         bool        must_use_password;
    2451                 :             :         char       *err;
    2452                 :             :         WalReceiverConn *wrconn;
    2453                 :             : 
    2454                 :             :         Assert(new_conninfo || orig_conninfo);
    2455                 :             : 
    2456                 :             :         /* Load the library providing us libpq calls. */
    2457                 :           7 :         load_file("libpqwalreceiver", false);
    2458                 :             : 
    2459                 :             :         /*
    2460                 :             :          * Try to connect to the publisher, using the new connection string if
    2461                 :             :          * available.
    2462                 :             :          */
    2463   [ +  -  -  + ]:           7 :         must_use_password = sub->passwordrequired && !sub->ownersuperuser;
    2464         [ -  + ]:           7 :         wrconn = walrcv_connect(new_conninfo ? new_conninfo : orig_conninfo,
    2465                 :             :                                 true, true, must_use_password, sub->name,
    2466                 :             :                                 &err);
    2467         [ -  + ]:           7 :         if (!wrconn)
    2468         [ #  # ]:           0 :             ereport(ERROR,
    2469                 :             :                     (errcode(ERRCODE_CONNECTION_FAILURE),
    2470                 :             :                      errmsg("subscription \"%s\" could not connect to the publisher: %s",
    2471                 :             :                             sub->name, err)));
    2472                 :             : 
    2473         [ +  - ]:           7 :         PG_TRY();
    2474                 :             :         {
    2475         [ +  + ]:           7 :             if (retain_dead_tuples)
    2476                 :           3 :                 CheckPubDeadTupleRetention(wrconn);
    2477                 :             : 
    2478                 :           7 :             check_publications_origin_tables(wrconn, sub->publications, false,
    2479                 :             :                                              retain_dead_tuples, origin, NULL, 0,
    2480                 :             :                                              sub->name);
    2481                 :             : 
    2482   [ +  +  +  + ]:           7 :             if (update_failover || update_two_phase)
    2483   [ +  +  +  + ]:           5 :                 walrcv_alter_slot(wrconn, sub->slotname,
    2484                 :             :                                   update_failover ? &opts.failover : NULL,
    2485                 :             :                                   update_two_phase ? &opts.twophase : NULL);
    2486                 :             :         }
    2487                 :           0 :         PG_FINALLY();
    2488                 :             :         {
    2489                 :           7 :             walrcv_disconnect(wrconn);
    2490                 :             :         }
    2491         [ -  + ]:           7 :         PG_END_TRY();
    2492                 :             :     }
    2493                 :             : 
    2494                 :         355 :     table_close(rel, RowExclusiveLock);
    2495                 :             : 
    2496         [ -  + ]:         355 :     InvokeObjectPostAlterHook(SubscriptionRelationId, subid, 0);
    2497                 :             : 
    2498                 :             :     /* Wake up related replication workers to handle this change quickly. */
    2499                 :         355 :     LogicalRepWorkersWakeupAtCommit(subid);
    2500                 :             : 
    2501                 :         355 :     return myself;
    2502                 :             : }
    2503                 :             : 
    2504                 :             : /*
    2505                 :             :  * Construct conninfo from a subscription's server. Like libpqrcv_connect(),
    2506                 :             :  * if an error occurs, set *err to the error message and return NULL.
    2507                 :             :  *
    2508                 :             :  * However, failures in ForeignServerConnectionString() may ereport(ERROR),
    2509                 :             :  * and (also like libpqrcv_connect) it's not worth adding the machinery to
    2510                 :             :  * pass all of those back to the caller just to cover this one case.
    2511                 :             :  */
    2512                 :             : static char *
    2513                 :           8 : construct_subserver_conninfo(Oid subserver, Oid subowner, char **err)
    2514                 :             : {
    2515                 :             :     AclResult   aclresult;
    2516                 :             :     ForeignServer *server;
    2517                 :             : 
    2518                 :           8 :     *err = NULL;
    2519                 :             : 
    2520                 :           8 :     server = GetForeignServer(subserver);
    2521                 :             : 
    2522                 :           8 :     aclresult = object_aclcheck(ForeignServerRelationId, subserver,
    2523                 :             :                                 subowner, ACL_USAGE);
    2524         [ +  + ]:           8 :     if (aclresult != ACLCHECK_OK)
    2525                 :             :     {
    2526                 :             :         /*
    2527                 :             :          * Unable to generate connection string because permissions on the
    2528                 :             :          * foreign server have been removed. Follow the same logic as an
    2529                 :             :          * unusable subconninfo (which will result in an ERROR later unless
    2530                 :             :          * slot_name = NONE).
    2531                 :             :          */
    2532                 :           4 :         *err = psprintf(_("subscription owner \"%s\" does not have permission on foreign server \"%s\""),
    2533                 :             :                         GetUserNameFromId(subowner, false),
    2534                 :             :                         server->servername);
    2535                 :           4 :         return NULL;
    2536                 :             :     }
    2537                 :             : 
    2538                 :           4 :     return ForeignServerConnectionString(subowner, server);
    2539                 :             : }
    2540                 :             : 
    2541                 :             : /*
    2542                 :             :  * Drop subscription's conflict log table
    2543                 :             :  *
    2544                 :             :  * The conflict log table is registered as an internal dependency of the
    2545                 :             :  * subscription. This function removes the dependency by performing a
    2546                 :             :  * cascading deletion on the subscription object, which in turn drops the
    2547                 :             :  * associated conflict log table.
    2548                 :             :  *
    2549                 :             :  * This is used to clean up conflict log tables that are no longer required,
    2550                 :             :  * preventing accumulation of stale or orphaned relations.
    2551                 :             :  *
    2552                 :             :  * NOTE:
    2553                 :             :  * Only conflict log tables are currently managed via this internal dependency
    2554                 :             :  * mechanism.
    2555                 :             :  */
    2556                 :             : static void
    2557                 :         172 : drop_sub_conflict_log_table(Oid subid, char *subname, Oid subconflictlogrelid)
    2558                 :             : {
    2559                 :             :     /* Drop any dependent conflict log table */
    2560         [ +  + ]:         172 :     if (OidIsValid(subconflictlogrelid))
    2561                 :             :     {
    2562                 :             :         ObjectAddress object;
    2563                 :             :         char       *conflictrelname;
    2564                 :             : 
    2565                 :          13 :         conflictrelname = get_rel_name(subconflictlogrelid);
    2566         [ -  + ]:          13 :         if (conflictrelname == NULL)
    2567         [ #  # ]:           0 :             elog(ERROR, "cache lookup failed for relation %u",
    2568                 :             :                  subconflictlogrelid);
    2569                 :             : 
    2570                 :             :         /*
    2571                 :             :          * By using PERFORM_DELETION_SKIP_ORIGINAL, we ensure that only the
    2572                 :             :          * conflict log table is deleted while the subscription remains.
    2573                 :             :          */
    2574                 :          13 :         ObjectAddressSet(object, SubscriptionRelationId, subid);
    2575                 :          13 :         performDeletion(&object, DROP_CASCADE,
    2576                 :             :                         PERFORM_DELETION_INTERNAL |
    2577                 :             :                         PERFORM_DELETION_SKIP_ORIGINAL);
    2578                 :             : 
    2579         [ +  + ]:          13 :         ereport(NOTICE,
    2580                 :             :                 errmsg("dropped conflict log table \"%s\" for subscription \"%s\"",
    2581                 :             :                        get_qualified_objname(PG_CONFLICT_NAMESPACE, conflictrelname),
    2582                 :             :                        subname));
    2583                 :             :     }
    2584                 :         172 : }
    2585                 :             : 
    2586                 :             : /*
    2587                 :             :  * Drop a subscription
    2588                 :             :  */
    2589                 :             : void
    2590                 :         180 : DropSubscription(DropSubscriptionStmt *stmt, bool isTopLevel)
    2591                 :             : {
    2592                 :             :     Relation    rel;
    2593                 :             :     ObjectAddress myself;
    2594                 :             :     HeapTuple   tup;
    2595                 :             :     Oid         subid;
    2596                 :             :     Oid         subowner;
    2597                 :             :     Oid         subserver;
    2598                 :             :     Oid         subconflictlogrelid;
    2599                 :         180 :     char       *subconninfo = NULL;
    2600                 :             :     Datum       datum;
    2601                 :             :     bool        isnull;
    2602                 :             :     char       *subname;
    2603                 :         180 :     char       *conninfo = NULL;
    2604                 :             :     char       *slotname;
    2605                 :             :     List       *subworkers;
    2606                 :             :     ListCell   *lc;
    2607                 :             :     char        originname[NAMEDATALEN];
    2608                 :         180 :     char       *err = NULL;
    2609                 :         180 :     WalReceiverConn *wrconn = NULL;
    2610                 :             :     Form_pg_subscription form;
    2611                 :             :     List       *rstates;
    2612                 :             :     bool        must_use_password;
    2613                 :             : 
    2614                 :             :     /*
    2615                 :             :      * The launcher may concurrently start a new worker for this subscription.
    2616                 :             :      * During initialization, the worker checks for subscription validity and
    2617                 :             :      * exits if the subscription has already been dropped. See
    2618                 :             :      * InitializeLogRepWorker.
    2619                 :             :      */
    2620                 :         180 :     rel = table_open(SubscriptionRelationId, RowExclusiveLock);
    2621                 :             : 
    2622                 :         180 :     tup = SearchSysCache2(SUBSCRIPTIONNAME, ObjectIdGetDatum(MyDatabaseId),
    2623                 :         180 :                           CStringGetDatum(stmt->subname));
    2624                 :             : 
    2625         [ +  + ]:         180 :     if (!HeapTupleIsValid(tup))
    2626                 :             :     {
    2627                 :           8 :         table_close(rel, NoLock);
    2628                 :             : 
    2629         [ +  + ]:           8 :         if (!stmt->missing_ok)
    2630         [ +  - ]:           4 :             ereport(ERROR,
    2631                 :             :                     (errcode(ERRCODE_UNDEFINED_OBJECT),
    2632                 :             :                      errmsg("subscription \"%s\" does not exist",
    2633                 :             :                             stmt->subname)));
    2634                 :             :         else
    2635         [ +  - ]:           4 :             ereport(NOTICE,
    2636                 :             :                     (errmsg("subscription \"%s\" does not exist, skipping",
    2637                 :             :                             stmt->subname)));
    2638                 :             : 
    2639                 :          86 :         return;
    2640                 :             :     }
    2641                 :             : 
    2642                 :         172 :     datum = SysCacheGetAttr(SUBSCRIPTIONOID, tup,
    2643                 :             :                             Anum_pg_subscription_subconninfo, &isnull);
    2644         [ +  + ]:         172 :     if (!isnull)
    2645                 :         155 :         subconninfo = TextDatumGetCString(datum);
    2646                 :             : 
    2647                 :         172 :     form = (Form_pg_subscription) GETSTRUCT(tup);
    2648                 :         172 :     subid = form->oid;
    2649                 :         172 :     subowner = form->subowner;
    2650                 :         172 :     subserver = form->subserver;
    2651                 :         172 :     subconflictlogrelid = form->subconflictlogrelid;
    2652   [ +  +  +  + ]:         172 :     must_use_password = !superuser_arg(subowner) && form->subpasswordrequired;
    2653                 :             : 
    2654                 :             :     /* must be owner */
    2655         [ -  + ]:         172 :     if (!object_ownercheck(SubscriptionRelationId, subid, GetUserId()))
    2656                 :           0 :         aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_SUBSCRIPTION,
    2657                 :           0 :                        stmt->subname);
    2658                 :             : 
    2659                 :             :     /* DROP hook for the subscription being removed */
    2660         [ -  + ]:         172 :     InvokeObjectDropHook(SubscriptionRelationId, subid, 0);
    2661                 :             : 
    2662                 :             :     /*
    2663                 :             :      * Lock the subscription so nobody else can do anything with it (including
    2664                 :             :      * the replication workers).
    2665                 :             :      */
    2666                 :         172 :     LockSharedObject(SubscriptionRelationId, subid, 0, AccessExclusiveLock);
    2667                 :             : 
    2668                 :             :     /* Get subname */
    2669                 :         172 :     datum = SysCacheGetAttrNotNull(SUBSCRIPTIONOID, tup,
    2670                 :             :                                    Anum_pg_subscription_subname);
    2671                 :         172 :     subname = pstrdup(NameStr(*DatumGetName(datum)));
    2672                 :             : 
    2673                 :             :     /* Get slotname */
    2674                 :         172 :     datum = SysCacheGetAttr(SUBSCRIPTIONOID, tup,
    2675                 :             :                             Anum_pg_subscription_subslotname, &isnull);
    2676         [ +  + ]:         172 :     if (!isnull)
    2677                 :          90 :         slotname = pstrdup(NameStr(*DatumGetName(datum)));
    2678                 :             :     else
    2679                 :          82 :         slotname = NULL;
    2680                 :             : 
    2681                 :             :     /*
    2682                 :             :      * Since dropping a replication slot is not transactional, the replication
    2683                 :             :      * slot stays dropped even if the transaction rolls back.  So we cannot
    2684                 :             :      * run DROP SUBSCRIPTION inside a transaction block if dropping the
    2685                 :             :      * replication slot.  Also, in this case, we report a message for dropping
    2686                 :             :      * the subscription to the cumulative stats system.
    2687                 :             :      *
    2688                 :             :      * XXX The command name should really be something like "DROP SUBSCRIPTION
    2689                 :             :      * of a subscription that is associated with a replication slot", but we
    2690                 :             :      * don't have the proper facilities for that.
    2691                 :             :      */
    2692         [ +  + ]:         172 :     if (slotname)
    2693                 :          90 :         PreventInTransactionBlock(isTopLevel, "DROP SUBSCRIPTION");
    2694                 :             : 
    2695                 :         168 :     ObjectAddressSet(myself, SubscriptionRelationId, subid);
    2696                 :         168 :     EventTriggerSQLDropAddObject(&myself, true, true);
    2697                 :             : 
    2698                 :             :     /* Remove the tuple from catalog. */
    2699                 :         168 :     CatalogTupleDelete(rel, &tup->t_self);
    2700                 :             : 
    2701                 :         168 :     ReleaseSysCache(tup);
    2702                 :             : 
    2703                 :             :     /*
    2704                 :             :      * Stop all the subscription workers immediately.
    2705                 :             :      *
    2706                 :             :      * This is necessary if we are dropping the replication slot, so that the
    2707                 :             :      * slot becomes accessible.
    2708                 :             :      *
    2709                 :             :      * It is also necessary if the subscription is disabled and was disabled
    2710                 :             :      * in the same transaction.  Then the workers haven't seen the disabling
    2711                 :             :      * yet and will still be running, leading to hangs later when we want to
    2712                 :             :      * drop the replication origin.  If the subscription was disabled before
    2713                 :             :      * this transaction, then there shouldn't be any workers left, so this
    2714                 :             :      * won't make a difference.
    2715                 :             :      *
    2716                 :             :      * New workers won't be started because we hold an exclusive lock on the
    2717                 :             :      * subscription till the end of the transaction.
    2718                 :             :      */
    2719                 :         168 :     subworkers = logicalrep_workers_find(subid, false, true);
    2720   [ +  +  +  +  :         251 :     foreach(lc, subworkers)
                   +  + ]
    2721                 :             :     {
    2722                 :          83 :         LogicalRepWorker *w = (LogicalRepWorker *) lfirst(lc);
    2723                 :             : 
    2724                 :          83 :         logicalrep_worker_stop(w->type, w->subid, w->relid);
    2725                 :             :     }
    2726                 :         168 :     list_free(subworkers);
    2727                 :             : 
    2728                 :             :     /*
    2729                 :             :      * Remove the no-longer-useful entry in the launcher's table of apply
    2730                 :             :      * worker start times.
    2731                 :             :      *
    2732                 :             :      * If this transaction rolls back, the launcher might restart a failed
    2733                 :             :      * apply worker before wal_retrieve_retry_interval milliseconds have
    2734                 :             :      * elapsed, but that's pretty harmless.
    2735                 :             :      */
    2736                 :         168 :     ApplyLauncherForgetWorkerStartTime(subid);
    2737                 :             : 
    2738                 :             :     /*
    2739                 :             :      * Cleanup of tablesync replication origins.
    2740                 :             :      *
    2741                 :             :      * Any READY-state relations would already have dealt with clean-ups.
    2742                 :             :      *
    2743                 :             :      * Note that the state can't change because we have already stopped both
    2744                 :             :      * the apply and tablesync workers and they can't restart because of
    2745                 :             :      * exclusive lock on the subscription.
    2746                 :             :      */
    2747                 :         168 :     rstates = GetSubscriptionRelations(subid, true, false, true);
    2748   [ +  +  +  +  :         173 :     foreach(lc, rstates)
                   +  + ]
    2749                 :             :     {
    2750                 :           5 :         SubscriptionRelState *rstate = (SubscriptionRelState *) lfirst(lc);
    2751                 :           5 :         Oid         relid = rstate->relid;
    2752                 :             : 
    2753                 :             :         /* Only cleanup resources of tablesync workers */
    2754         [ -  + ]:           5 :         if (!OidIsValid(relid))
    2755                 :           0 :             continue;
    2756                 :             : 
    2757                 :             :         /*
    2758                 :             :          * Drop the tablesync's origin tracking if exists.
    2759                 :             :          *
    2760                 :             :          * It is possible that the origin is not yet created for tablesync
    2761                 :             :          * worker so passing missing_ok = true. This can happen for the states
    2762                 :             :          * before SUBREL_STATE_DATASYNC.
    2763                 :             :          */
    2764                 :           5 :         ReplicationOriginNameForLogicalRep(subid, relid, originname,
    2765                 :             :                                            sizeof(originname));
    2766                 :           5 :         replorigin_drop_by_name(originname, true, false);
    2767                 :             :     }
    2768                 :             : 
    2769                 :             :     /* Drop subscription's conflict log table */
    2770                 :         168 :     drop_sub_conflict_log_table(subid, subname, subconflictlogrelid);
    2771                 :             : 
    2772                 :             :     /* Clean up dependencies */
    2773                 :         168 :     deleteDependencyRecordsFor(SubscriptionRelationId, subid, false);
    2774                 :         168 :     deleteSharedDependencyRecordsFor(SubscriptionRelationId, subid, 0);
    2775                 :             : 
    2776                 :             :     /* Remove any associated relation synchronization states. */
    2777                 :         168 :     RemoveSubscriptionRel(subid, InvalidOid);
    2778                 :             : 
    2779                 :             :     /* Remove the origin tracking if exists. */
    2780                 :         168 :     ReplicationOriginNameForLogicalRep(subid, InvalidOid, originname, sizeof(originname));
    2781                 :         168 :     replorigin_drop_by_name(originname, true, false);
    2782                 :             : 
    2783                 :             :     /*
    2784                 :             :      * Tell the cumulative stats system that the subscription is getting
    2785                 :             :      * dropped.
    2786                 :             :      */
    2787                 :         168 :     pgstat_drop_subscription(subid);
    2788                 :             : 
    2789                 :             :     /*
    2790                 :             :      * If there is no slot associated with the subscription, we can finish
    2791                 :             :      * here.
    2792                 :             :      */
    2793   [ +  +  +  - ]:         168 :     if (!slotname && rstates == NIL)
    2794                 :             :     {
    2795                 :          82 :         table_close(rel, NoLock);
    2796                 :          82 :         return;
    2797                 :             :     }
    2798                 :             : 
    2799                 :             :     /*
    2800                 :             :      * Try to acquire the connection necessary for dropping slots.
    2801                 :             :      *
    2802                 :             :      * Note: If the slotname is NONE/NULL then we allow the command to finish
    2803                 :             :      * and users need to manually cleanup the apply and tablesync worker slots
    2804                 :             :      * later.
    2805                 :             :      *
    2806                 :             :      * This has to be at the end because otherwise if there is an error while
    2807                 :             :      * doing the database operations we won't be able to rollback dropped
    2808                 :             :      * slot.
    2809                 :             :      */
    2810                 :          86 :     load_file("libpqwalreceiver", false);
    2811                 :             : 
    2812         [ +  + ]:          86 :     if (OidIsValid(subserver))
    2813                 :           8 :         conninfo = construct_subserver_conninfo(subserver, subowner, &err);
    2814                 :             :     else
    2815                 :          78 :         conninfo = subconninfo;
    2816                 :             : 
    2817         [ +  + ]:          82 :     if (conninfo)
    2818                 :          78 :         wrconn = walrcv_connect(conninfo, true, true, must_use_password,
    2819                 :             :                                 subname, &err);
    2820                 :             : 
    2821         [ +  + ]:          82 :     if (wrconn == NULL)
    2822                 :             :     {
    2823         [ -  + ]:           4 :         if (!slotname)
    2824                 :             :         {
    2825                 :             :             /* be tidy */
    2826                 :           0 :             list_free(rstates);
    2827                 :           0 :             table_close(rel, NoLock);
    2828                 :           0 :             return;
    2829                 :             :         }
    2830                 :             :         else
    2831                 :             :         {
    2832                 :           4 :             ReportSlotConnectionError(rstates, subid, slotname, err);
    2833                 :             :         }
    2834                 :             :     }
    2835                 :             : 
    2836         [ +  + ]:          78 :     PG_TRY();
    2837                 :             :     {
    2838   [ +  +  +  +  :          83 :         foreach(lc, rstates)
                   +  + ]
    2839                 :             :         {
    2840                 :           5 :             SubscriptionRelState *rstate = (SubscriptionRelState *) lfirst(lc);
    2841                 :           5 :             Oid         relid = rstate->relid;
    2842                 :             : 
    2843                 :             :             /* Only cleanup resources of tablesync workers */
    2844         [ -  + ]:           5 :             if (!OidIsValid(relid))
    2845                 :           0 :                 continue;
    2846                 :             : 
    2847                 :             :             /*
    2848                 :             :              * Drop the tablesync slots associated with removed tables.
    2849                 :             :              *
    2850                 :             :              * For SYNCDONE/READY states, the tablesync slot is known to have
    2851                 :             :              * already been dropped by the tablesync worker.
    2852                 :             :              *
    2853                 :             :              * For other states, there is no certainty, maybe the slot does
    2854                 :             :              * not exist yet. Also, if we fail after removing some of the
    2855                 :             :              * slots, next time, it will again try to drop already dropped
    2856                 :             :              * slots and fail. For these reasons, we allow missing_ok = true
    2857                 :             :              * for the drop.
    2858                 :             :              */
    2859         [ +  + ]:           5 :             if (rstate->state != SUBREL_STATE_SYNCDONE)
    2860                 :             :             {
    2861                 :           3 :                 char        syncslotname[NAMEDATALEN] = {0};
    2862                 :             : 
    2863                 :           3 :                 ReplicationSlotNameForTablesync(subid, relid, syncslotname,
    2864                 :             :                                                 sizeof(syncslotname));
    2865                 :           3 :                 ReplicationSlotDropAtPubNode(wrconn, syncslotname, true);
    2866                 :             :             }
    2867                 :             :         }
    2868                 :             : 
    2869                 :          78 :         list_free(rstates);
    2870                 :             : 
    2871                 :             :         /*
    2872                 :             :          * If there is a slot associated with the subscription, then drop the
    2873                 :             :          * replication slot at the publisher.
    2874                 :             :          */
    2875         [ +  - ]:          78 :         if (slotname)
    2876                 :          78 :             ReplicationSlotDropAtPubNode(wrconn, slotname, false);
    2877                 :             :     }
    2878                 :           1 :     PG_FINALLY();
    2879                 :             :     {
    2880                 :          78 :         walrcv_disconnect(wrconn);
    2881                 :             :     }
    2882         [ +  + ]:          78 :     PG_END_TRY();
    2883                 :             : 
    2884                 :          77 :     table_close(rel, NoLock);
    2885                 :             : }
    2886                 :             : 
    2887                 :             : /*
    2888                 :             :  * Drop the replication slot at the publisher node using the replication
    2889                 :             :  * connection.
    2890                 :             :  *
    2891                 :             :  * missing_ok - if true then only issue a LOG message if the slot doesn't
    2892                 :             :  * exist.
    2893                 :             :  */
    2894                 :             : void
    2895                 :         291 : ReplicationSlotDropAtPubNode(WalReceiverConn *wrconn, char *slotname, bool missing_ok)
    2896                 :             : {
    2897                 :             :     StringInfoData cmd;
    2898                 :             : 
    2899                 :             :     Assert(wrconn);
    2900                 :             : 
    2901                 :         291 :     load_file("libpqwalreceiver", false);
    2902                 :             : 
    2903                 :         291 :     initStringInfo(&cmd);
    2904                 :         291 :     appendStringInfoString(&cmd, "DROP_REPLICATION_SLOT ");
    2905                 :         291 :     appendQuotedIdentifier(&cmd, slotname);
    2906                 :         291 :     appendStringInfoString(&cmd, " WAIT");
    2907                 :             : 
    2908         [ +  + ]:         291 :     PG_TRY();
    2909                 :             :     {
    2910                 :             :         WalRcvExecResult *res;
    2911                 :             : 
    2912                 :         291 :         res = walrcv_exec(wrconn, cmd.data, 0, NULL);
    2913                 :             : 
    2914         [ +  + ]:         291 :         if (res->status == WALRCV_OK_COMMAND)
    2915                 :             :         {
    2916                 :             :             /* NOTICE. Success. */
    2917         [ +  + ]:         289 :             ereport(NOTICE,
    2918                 :             :                     (errmsg("dropped replication slot \"%s\" on publisher",
    2919                 :             :                             slotname)));
    2920                 :             :         }
    2921   [ +  -  +  + ]:           2 :         else if (res->status == WALRCV_ERROR &&
    2922                 :           1 :                  missing_ok &&
    2923         [ +  - ]:           1 :                  res->sqlstate == ERRCODE_UNDEFINED_OBJECT)
    2924                 :             :         {
    2925                 :             :             /* LOG. Error, but missing_ok = true. */
    2926         [ +  - ]:           1 :             ereport(LOG,
    2927                 :             :                     (errmsg("could not drop replication slot \"%s\" on publisher: %s",
    2928                 :             :                             slotname, res->err)));
    2929                 :             :         }
    2930                 :             :         else
    2931                 :             :         {
    2932                 :             :             /* ERROR. */
    2933         [ +  - ]:           1 :             ereport(ERROR,
    2934                 :             :                     (errcode(ERRCODE_CONNECTION_FAILURE),
    2935                 :             :                      errmsg("could not drop replication slot \"%s\" on publisher: %s",
    2936                 :             :                             slotname, res->err)));
    2937                 :             :         }
    2938                 :             : 
    2939                 :         290 :         walrcv_clear_result(res);
    2940                 :             :     }
    2941                 :           1 :     PG_FINALLY();
    2942                 :             :     {
    2943                 :         291 :         pfree(cmd.data);
    2944                 :             :     }
    2945         [ +  + ]:         291 :     PG_END_TRY();
    2946                 :         290 : }
    2947                 :             : 
    2948                 :             : /*
    2949                 :             :  * Internal workhorse for changing a subscription owner
    2950                 :             :  */
    2951                 :             : static void
    2952                 :          28 : AlterSubscriptionOwner_internal(Relation rel, HeapTuple tup, Oid newOwnerId)
    2953                 :             : {
    2954                 :             :     Form_pg_subscription form;
    2955                 :             :     AclResult   aclresult;
    2956                 :             : 
    2957                 :          28 :     form = (Form_pg_subscription) GETSTRUCT(tup);
    2958                 :             : 
    2959                 :             :     /* Must only alter subscriptions belonging to the current database. */
    2960                 :             :     Assert(form->subdbid == MyDatabaseId);
    2961                 :             : 
    2962         [ +  + ]:          28 :     if (form->subowner == newOwnerId)
    2963                 :           2 :         return;
    2964                 :             : 
    2965         [ -  + ]:          26 :     if (!object_ownercheck(SubscriptionRelationId, form->oid, GetUserId()))
    2966                 :           0 :         aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_SUBSCRIPTION,
    2967                 :           0 :                        NameStr(form->subname));
    2968                 :             : 
    2969                 :             :     /*
    2970                 :             :      * Don't allow non-superuser modification of a subscription with
    2971                 :             :      * password_required=false.
    2972                 :             :      */
    2973   [ -  +  -  - ]:          26 :     if (!form->subpasswordrequired && !superuser())
    2974         [ #  # ]:           0 :         ereport(ERROR,
    2975                 :             :                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
    2976                 :             :                  errmsg("password_required=false is superuser-only"),
    2977                 :             :                  errhint("Subscriptions with the password_required option set to false may only be created or modified by the superuser.")));
    2978                 :             : 
    2979                 :             :     /* Must be able to become new owner */
    2980                 :          26 :     check_can_set_role(GetUserId(), newOwnerId);
    2981                 :             : 
    2982                 :             :     /*
    2983                 :             :      * current owner must have CREATE on database
    2984                 :             :      *
    2985                 :             :      * This is consistent with how ALTER SCHEMA ... OWNER TO works, but some
    2986                 :             :      * other object types behave differently (e.g. you can't give a table to a
    2987                 :             :      * user who lacks CREATE privileges on a schema).
    2988                 :             :      */
    2989                 :          22 :     aclresult = object_aclcheck(DatabaseRelationId, MyDatabaseId,
    2990                 :             :                                 GetUserId(), ACL_CREATE);
    2991         [ -  + ]:          22 :     if (aclresult != ACLCHECK_OK)
    2992                 :           0 :         aclcheck_error(aclresult, OBJECT_DATABASE,
    2993                 :           0 :                        get_database_name(MyDatabaseId));
    2994                 :             : 
    2995                 :             :     /*
    2996                 :             :      * The privileges will be checked before the connection is actually used,
    2997                 :             :      * so it does not need to be done here. Avoid unnecessary risk of errors
    2998                 :             :      * here, which could interfere with restore.
    2999                 :             :      *
    3000                 :             :      * However, it is convenient to check if a user mapping exists, and raise
    3001                 :             :      * a WARNING if not.
    3002                 :             :      */
    3003         [ +  + ]:          22 :     if (OidIsValid(form->subserver))
    3004                 :           9 :         GetUserMappingExtended(newOwnerId, form->subserver, WARNING);
    3005                 :             : 
    3006                 :          22 :     form->subowner = newOwnerId;
    3007                 :          22 :     CatalogTupleUpdate(rel, &tup->t_self, tup);
    3008                 :             : 
    3009                 :             :     /* Update owner of the conflict log table if it exists. */
    3010         [ +  + ]:          22 :     if (OidIsValid(form->subconflictlogrelid))
    3011                 :           8 :         ATExecChangeOwner(form->subconflictlogrelid, newOwnerId, true,
    3012                 :             :                           AccessExclusiveLock);
    3013                 :             : 
    3014                 :             :     /* Update owner dependency reference */
    3015                 :          22 :     changeDependencyOnOwner(SubscriptionRelationId,
    3016                 :             :                             form->oid,
    3017                 :             :                             newOwnerId);
    3018                 :             : 
    3019         [ -  + ]:          22 :     InvokeObjectPostAlterHook(SubscriptionRelationId,
    3020                 :             :                               form->oid, 0);
    3021                 :             : 
    3022                 :             :     /* Wake up related background processes to handle this change quickly. */
    3023                 :          22 :     ApplyLauncherWakeupAtCommit();
    3024                 :          22 :     LogicalRepWorkersWakeupAtCommit(form->oid);
    3025                 :             : }
    3026                 :             : 
    3027                 :             : /*
    3028                 :             :  * Change subscription owner -- by name
    3029                 :             :  */
    3030                 :             : ObjectAddress
    3031                 :          27 : AlterSubscriptionOwner(const char *name, Oid newOwnerId)
    3032                 :             : {
    3033                 :             :     Oid         subid;
    3034                 :             :     HeapTuple   tup;
    3035                 :             :     Relation    rel;
    3036                 :             :     ObjectAddress address;
    3037                 :             :     Form_pg_subscription form;
    3038                 :             : 
    3039                 :          27 :     rel = table_open(SubscriptionRelationId, RowExclusiveLock);
    3040                 :             : 
    3041                 :          27 :     tup = SearchSysCacheCopy2(SUBSCRIPTIONNAME, ObjectIdGetDatum(MyDatabaseId),
    3042                 :             :                               CStringGetDatum(name));
    3043                 :             : 
    3044         [ -  + ]:          27 :     if (!HeapTupleIsValid(tup))
    3045         [ #  # ]:           0 :         ereport(ERROR,
    3046                 :             :                 (errcode(ERRCODE_UNDEFINED_OBJECT),
    3047                 :             :                  errmsg("subscription \"%s\" does not exist", name)));
    3048                 :             : 
    3049                 :          27 :     form = (Form_pg_subscription) GETSTRUCT(tup);
    3050                 :          27 :     subid = form->oid;
    3051                 :             : 
    3052                 :          27 :     AlterSubscriptionOwner_internal(rel, tup, newOwnerId);
    3053                 :             : 
    3054                 :          23 :     ObjectAddressSet(address, SubscriptionRelationId, subid);
    3055                 :             : 
    3056                 :          23 :     heap_freetuple(tup);
    3057                 :             : 
    3058                 :          23 :     table_close(rel, RowExclusiveLock);
    3059                 :             : 
    3060                 :          23 :     return address;
    3061                 :             : }
    3062                 :             : 
    3063                 :             : /*
    3064                 :             :  * Change subscription owner -- by OID
    3065                 :             :  */
    3066                 :             : void
    3067                 :           2 : AlterSubscriptionOwner_oid(Oid subid, Oid newOwnerId)
    3068                 :             : {
    3069                 :             :     HeapTuple   tup;
    3070                 :             :     Relation    rel;
    3071                 :             :     Form_pg_subscription form;
    3072                 :             : 
    3073                 :           2 :     rel = table_open(SubscriptionRelationId, RowExclusiveLock);
    3074                 :             : 
    3075                 :           2 :     tup = SearchSysCacheCopy1(SUBSCRIPTIONOID, ObjectIdGetDatum(subid));
    3076                 :             : 
    3077         [ -  + ]:           2 :     if (!HeapTupleIsValid(tup))
    3078         [ #  # ]:           0 :         ereport(ERROR,
    3079                 :             :                 (errcode(ERRCODE_UNDEFINED_OBJECT),
    3080                 :             :                  errmsg("subscription with OID %u does not exist", subid)));
    3081                 :             : 
    3082                 :           2 :     form = (Form_pg_subscription) GETSTRUCT(tup);
    3083                 :             : 
    3084                 :             :     /*
    3085                 :             :      * Don't process subscriptions belonging to other databases. While
    3086                 :             :      * pg_subscription is a shared catalog, subscriptions refer to db-local
    3087                 :             :      * objects which exist only in the database identified by subdbid.
    3088                 :             :      */
    3089         [ +  + ]:           2 :     if (form->subdbid == MyDatabaseId)
    3090                 :           1 :         AlterSubscriptionOwner_internal(rel, tup, newOwnerId);
    3091                 :             : 
    3092                 :           2 :     heap_freetuple(tup);
    3093                 :             : 
    3094                 :           2 :     table_close(rel, RowExclusiveLock);
    3095                 :           2 : }
    3096                 :             : 
    3097                 :             : /*
    3098                 :             :  * Check and log a warning if the publisher has subscribed to the same table,
    3099                 :             :  * its partition ancestors (if it's a partition), or its partition children (if
    3100                 :             :  * it's a partitioned table), from some other publishers. This check is
    3101                 :             :  * required in the following scenarios:
    3102                 :             :  *
    3103                 :             :  * 1) For CREATE SUBSCRIPTION and ALTER SUBSCRIPTION ... REFRESH PUBLICATION
    3104                 :             :  *    statements with "copy_data = true" and "origin = none":
    3105                 :             :  *    - Warn the user that data with an origin might have been copied.
    3106                 :             :  *    - This check is skipped for tables already added, as incremental sync via
    3107                 :             :  *      WAL allows origin tracking. The list of such tables is in
    3108                 :             :  *      subrel_local_oids.
    3109                 :             :  *
    3110                 :             :  * 2) For CREATE SUBSCRIPTION and ALTER SUBSCRIPTION ... REFRESH PUBLICATION
    3111                 :             :  *    statements with "retain_dead_tuples = true" and "origin = any", and for
    3112                 :             :  *    ALTER SUBSCRIPTION statements that modify retain_dead_tuples or origin,
    3113                 :             :  *    or when the publisher's status changes (e.g., due to a connection string
    3114                 :             :  *    update):
    3115                 :             :  *    - Warn the user that only conflict detection info for local changes on
    3116                 :             :  *      the publisher is retained. Data from other origins may lack sufficient
    3117                 :             :  *      details for reliable conflict detection.
    3118                 :             :  *    - See comments atop worker.c for more details.
    3119                 :             :  */
    3120                 :             : static void
    3121                 :         171 : check_publications_origin_tables(WalReceiverConn *wrconn, List *publications,
    3122                 :             :                                  bool copydata, bool retain_dead_tuples,
    3123                 :             :                                  char *origin, Oid *subrel_local_oids,
    3124                 :             :                                  int subrel_count, char *subname)
    3125                 :             : {
    3126                 :             :     WalRcvExecResult *res;
    3127                 :             :     StringInfoData cmd;
    3128                 :             :     TupleTableSlot *slot;
    3129                 :         171 :     Oid         tableRow[1] = {TEXTOID};
    3130                 :         171 :     List       *publist = NIL;
    3131                 :             :     int         i;
    3132                 :             :     bool        check_rdt;
    3133                 :             :     bool        check_table_sync;
    3134   [ +  -  +  + ]:         342 :     bool        origin_none = origin &&
    3135                 :         171 :         pg_strcasecmp(origin, LOGICALREP_ORIGIN_NONE) == 0;
    3136                 :             : 
    3137                 :             :     /*
    3138                 :             :      * Enable retain_dead_tuples checks only when origin is set to 'any',
    3139                 :             :      * since with origin='none' only local changes are replicated to the
    3140                 :             :      * subscriber.
    3141                 :             :      */
    3142   [ +  +  +  + ]:         171 :     check_rdt = retain_dead_tuples && !origin_none;
    3143                 :             : 
    3144                 :             :     /*
    3145                 :             :      * Enable table synchronization checks only when origin is 'none', to
    3146                 :             :      * ensure that data from other origins is not inadvertently copied.
    3147                 :             :      */
    3148   [ +  +  +  + ]:         171 :     check_table_sync = copydata && origin_none;
    3149                 :             : 
    3150                 :             :     /* retain_dead_tuples and table sync checks occur separately */
    3151                 :             :     Assert(!(check_rdt && check_table_sync));
    3152                 :             : 
    3153                 :             :     /* Return if no checks are required */
    3154   [ +  +  +  + ]:         171 :     if (!check_rdt && !check_table_sync)
    3155                 :         158 :         return;
    3156                 :             : 
    3157                 :          13 :     initStringInfo(&cmd);
    3158                 :          13 :     appendStringInfoString(&cmd,
    3159                 :             :                            "SELECT DISTINCT P.pubname AS pubname\n"
    3160                 :             :                            "FROM pg_publication P,\n"
    3161                 :             :                            "     LATERAL pg_get_publication_tables(P.pubname) GPT\n"
    3162                 :             :                            "     JOIN pg_subscription_rel PS ON (GPT.relid = PS.srrelid OR"
    3163                 :             :                            "     GPT.relid IN (SELECT relid FROM pg_partition_ancestors(PS.srrelid) UNION"
    3164                 :             :                            "                   SELECT relid FROM pg_partition_tree(PS.srrelid))),\n"
    3165                 :             :                            "     pg_class C JOIN pg_namespace N ON (N.oid = C.relnamespace)\n"
    3166                 :             :                            "WHERE C.oid = GPT.relid AND P.pubname IN (");
    3167                 :          13 :     GetPublicationsStr(publications, &cmd, true);
    3168                 :          13 :     appendStringInfoString(&cmd, ")\n");
    3169                 :             : 
    3170                 :             :     /*
    3171                 :             :      * In case of ALTER SUBSCRIPTION ... REFRESH PUBLICATION,
    3172                 :             :      * subrel_local_oids contains the list of relation oids that are already
    3173                 :             :      * present on the subscriber. This check should be skipped for these
    3174                 :             :      * tables if checking for table sync scenario. However, when handling the
    3175                 :             :      * retain_dead_tuples scenario, ensure all tables are checked, as some
    3176                 :             :      * existing tables may now include changes from other origins due to newly
    3177                 :             :      * created subscriptions on the publisher.
    3178                 :             :      */
    3179         [ +  + ]:          13 :     if (check_table_sync)
    3180                 :             :     {
    3181         [ +  + ]:          14 :         for (i = 0; i < subrel_count; i++)
    3182                 :             :         {
    3183                 :           4 :             Oid         relid = subrel_local_oids[i];
    3184                 :           4 :             char       *schemaname = get_namespace_name(get_rel_namespace(relid));
    3185                 :           4 :             char       *tablename = get_rel_name(relid);
    3186                 :           4 :             char       *schemaname_lit = quote_literal_cstr(schemaname);
    3187                 :           4 :             char       *tablename_lit = quote_literal_cstr(tablename);
    3188                 :             : 
    3189                 :           4 :             appendStringInfo(&cmd, "AND NOT (N.nspname = %s AND C.relname = %s)\n",
    3190                 :             :                              schemaname_lit, tablename_lit);
    3191                 :             : 
    3192                 :           4 :             pfree(schemaname_lit);
    3193                 :           4 :             pfree(tablename_lit);
    3194                 :             :         }
    3195                 :             :     }
    3196                 :             : 
    3197                 :          13 :     res = walrcv_exec(wrconn, cmd.data, 1, tableRow);
    3198                 :          13 :     pfree(cmd.data);
    3199                 :             : 
    3200         [ -  + ]:          13 :     if (res->status != WALRCV_OK_TUPLES)
    3201         [ #  # ]:           0 :         ereport(ERROR,
    3202                 :             :                 (errcode(ERRCODE_CONNECTION_FAILURE),
    3203                 :             :                  errmsg("could not receive list of replicated tables from the publisher: %s",
    3204                 :             :                         res->err)));
    3205                 :             : 
    3206                 :             :     /* Process publications. */
    3207                 :          13 :     slot = MakeSingleTupleTableSlot(res->tupledesc, &TTSOpsMinimalTuple);
    3208         [ +  + ]:          18 :     while (tuplestore_gettupleslot(res->tuplestore, true, false, slot))
    3209                 :             :     {
    3210                 :             :         char       *pubname;
    3211                 :             :         bool        isnull;
    3212                 :             : 
    3213                 :           5 :         pubname = TextDatumGetCString(slot_getattr(slot, 1, &isnull));
    3214                 :             :         Assert(!isnull);
    3215                 :             : 
    3216                 :           5 :         ExecClearTuple(slot);
    3217                 :           5 :         publist = list_append_unique(publist, makeString(pubname));
    3218                 :             :     }
    3219                 :             : 
    3220                 :             :     /*
    3221                 :             :      * Log a warning if the publisher has subscribed to the same table from
    3222                 :             :      * some other publisher. We cannot know the origin of data during the
    3223                 :             :      * initial sync. Data origins can be found only from the WAL by looking at
    3224                 :             :      * the origin id.
    3225                 :             :      *
    3226                 :             :      * XXX: For simplicity, we don't check whether the table has any data or
    3227                 :             :      * not. If the table doesn't have any data then we don't need to
    3228                 :             :      * distinguish between data having origin and data not having origin so we
    3229                 :             :      * can avoid logging a warning for table sync scenario.
    3230                 :             :      */
    3231         [ +  + ]:          13 :     if (publist)
    3232                 :             :     {
    3233                 :             :         StringInfoData pubnames;
    3234                 :             : 
    3235                 :             :         /* Prepare the list of publication(s) for warning message. */
    3236                 :           5 :         initStringInfo(&pubnames);
    3237                 :           5 :         GetPublicationsStr(publist, &pubnames, false);
    3238                 :             : 
    3239         [ +  + ]:           5 :         if (check_table_sync)
    3240         [ +  - ]:           4 :             ereport(WARNING,
    3241                 :             :                     errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    3242                 :             :                     errmsg("subscription \"%s\" requested copy_data with origin = NONE but might copy data that had a different origin",
    3243                 :             :                            subname),
    3244                 :             :                     errdetail_plural("The subscription subscribes to a publication (%s) that contains tables that are written to by other subscriptions.",
    3245                 :             :                                      "The subscription subscribes to publications (%s) that contain tables that are written to by other subscriptions.",
    3246                 :             :                                      list_length(publist), pubnames.data),
    3247                 :             :                     errhint("Verify that initial data copied from the publisher tables did not come from other origins."));
    3248                 :             :         else
    3249         [ +  - ]:           1 :             ereport(WARNING,
    3250                 :             :                     errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    3251                 :             :                     errmsg("subscription \"%s\" enabled retain_dead_tuples but might not reliably detect conflicts for changes from different origins",
    3252                 :             :                            subname),
    3253                 :             :                     errdetail_plural("The subscription subscribes to a publication (%s) that contains tables that are written to by other subscriptions.",
    3254                 :             :                                      "The subscription subscribes to publications (%s) that contain tables that are written to by other subscriptions.",
    3255                 :             :                                      list_length(publist), pubnames.data),
    3256                 :             :                     errhint("Consider using origin = NONE or disabling retain_dead_tuples."));
    3257                 :             :     }
    3258                 :             : 
    3259                 :          13 :     ExecDropSingleTupleTableSlot(slot);
    3260                 :             : 
    3261                 :          13 :     walrcv_clear_result(res);
    3262                 :             : }
    3263                 :             : 
    3264                 :             : /*
    3265                 :             :  * This function is similar to check_publications_origin_tables and serves
    3266                 :             :  * same purpose for sequences.
    3267                 :             :  */
    3268                 :             : static void
    3269                 :         169 : check_publications_origin_sequences(WalReceiverConn *wrconn, List *publications,
    3270                 :             :                                     bool copydata, char *origin,
    3271                 :             :                                     Oid *subrel_local_oids, int subrel_count,
    3272                 :             :                                     char *subname)
    3273                 :             : {
    3274                 :             :     WalRcvExecResult *res;
    3275                 :             :     StringInfoData cmd;
    3276                 :             :     TupleTableSlot *slot;
    3277                 :         169 :     Oid         tableRow[1] = {TEXTOID};
    3278                 :         169 :     List       *publist = NIL;
    3279                 :             : 
    3280                 :             :     /*
    3281                 :             :      * Enable sequence synchronization checks only when origin is 'none' , to
    3282                 :             :      * ensure that sequence data from other origins is not inadvertently
    3283                 :             :      * copied. This check is necessary if the publisher is running PG19 or
    3284                 :             :      * later, where logical replication sequence synchronization is supported.
    3285                 :             :      */
    3286   [ +  +  +  +  :         179 :     if (!copydata || pg_strcasecmp(origin, LOGICALREP_ORIGIN_NONE) != 0 ||
                   -  + ]
    3287                 :          10 :         walrcv_server_version(wrconn) < 190000)
    3288                 :         159 :         return;
    3289                 :             : 
    3290                 :          10 :     initStringInfo(&cmd);
    3291                 :          10 :     appendStringInfoString(&cmd,
    3292                 :             :                            "SELECT DISTINCT P.pubname AS pubname\n"
    3293                 :             :                            "FROM pg_publication P,\n"
    3294                 :             :                            "     LATERAL pg_get_publication_sequences(P.pubname) GPS\n"
    3295                 :             :                            "     JOIN pg_subscription_rel PS ON (GPS.relid = PS.srrelid),\n"
    3296                 :             :                            "     pg_class C JOIN pg_namespace N ON (N.oid = C.relnamespace)\n"
    3297                 :             :                            "WHERE C.oid = GPS.relid AND P.pubname IN (");
    3298                 :             : 
    3299                 :          10 :     GetPublicationsStr(publications, &cmd, true);
    3300                 :          10 :     appendStringInfoString(&cmd, ")\n");
    3301                 :             : 
    3302                 :             :     /*
    3303                 :             :      * In case of ALTER SUBSCRIPTION ... REFRESH PUBLICATION,
    3304                 :             :      * subrel_local_oids contains the list of relations that are already
    3305                 :             :      * present on the subscriber. This check should be skipped as these will
    3306                 :             :      * not be re-synced.
    3307                 :             :      */
    3308         [ -  + ]:          10 :     for (int i = 0; i < subrel_count; i++)
    3309                 :             :     {
    3310                 :           0 :         Oid         relid = subrel_local_oids[i];
    3311                 :           0 :         char       *schemaname = get_namespace_name(get_rel_namespace(relid));
    3312                 :           0 :         char       *seqname = get_rel_name(relid);
    3313                 :           0 :         char       *schemaname_lit = quote_literal_cstr(schemaname);
    3314                 :           0 :         char       *seqname_lit = quote_literal_cstr(seqname);
    3315                 :             : 
    3316                 :           0 :         appendStringInfo(&cmd,
    3317                 :             :                          "AND NOT (N.nspname = %s AND C.relname = %s)\n",
    3318                 :             :                          schemaname_lit, seqname_lit);
    3319                 :             : 
    3320                 :           0 :         pfree(schemaname_lit);
    3321                 :           0 :         pfree(seqname_lit);
    3322                 :             :     }
    3323                 :             : 
    3324                 :          10 :     res = walrcv_exec(wrconn, cmd.data, 1, tableRow);
    3325                 :          10 :     pfree(cmd.data);
    3326                 :             : 
    3327         [ -  + ]:          10 :     if (res->status != WALRCV_OK_TUPLES)
    3328         [ #  # ]:           0 :         ereport(ERROR,
    3329                 :             :                 (errcode(ERRCODE_CONNECTION_FAILURE),
    3330                 :             :                  errmsg("could not receive list of replicated sequences from the publisher: %s",
    3331                 :             :                         res->err)));
    3332                 :             : 
    3333                 :             :     /* Process publications. */
    3334                 :          10 :     slot = MakeSingleTupleTableSlot(res->tupledesc, &TTSOpsMinimalTuple);
    3335         [ -  + ]:          10 :     while (tuplestore_gettupleslot(res->tuplestore, true, false, slot))
    3336                 :             :     {
    3337                 :             :         char       *pubname;
    3338                 :             :         bool        isnull;
    3339                 :             : 
    3340                 :           0 :         pubname = TextDatumGetCString(slot_getattr(slot, 1, &isnull));
    3341                 :             :         Assert(!isnull);
    3342                 :             : 
    3343                 :           0 :         ExecClearTuple(slot);
    3344                 :           0 :         publist = list_append_unique(publist, makeString(pubname));
    3345                 :             :     }
    3346                 :             : 
    3347                 :             :     /*
    3348                 :             :      * Log a warning if the publisher has subscribed to the same sequence from
    3349                 :             :      * some other publisher. We cannot know the origin of sequences data
    3350                 :             :      * during the initial sync.
    3351                 :             :      */
    3352         [ -  + ]:          10 :     if (publist)
    3353                 :             :     {
    3354                 :             :         StringInfoData pubnames;
    3355                 :             : 
    3356                 :             :         /* Prepare the list of publication(s) for warning message. */
    3357                 :           0 :         initStringInfo(&pubnames);
    3358                 :           0 :         GetPublicationsStr(publist, &pubnames, false);
    3359                 :             : 
    3360         [ #  # ]:           0 :         ereport(WARNING,
    3361                 :             :                 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    3362                 :             :                 errmsg("subscription \"%s\" requested origin = NONE but might synchronize sequence values that had a different origin",
    3363                 :             :                        subname),
    3364                 :             :                 errdetail_plural("The subscription subscribes to a publication (%s) that contains sequences that are synchronized from other subscriptions.",
    3365                 :             :                                  "The subscription subscribes to publications (%s) that contain sequences that are synchronized from other subscriptions.",
    3366                 :             :                                  list_length(publist), pubnames.data),
    3367                 :             :                 errhint("Verify that the initial values copied from the publisher sequences did not come from other origins."));
    3368                 :             :     }
    3369                 :             : 
    3370                 :          10 :     ExecDropSingleTupleTableSlot(slot);
    3371                 :             : 
    3372                 :          10 :     walrcv_clear_result(res);
    3373                 :             : }
    3374                 :             : 
    3375                 :             : /*
    3376                 :             :  * Determine whether the retain_dead_tuples can be enabled based on the
    3377                 :             :  * publisher's status.
    3378                 :             :  *
    3379                 :             :  * This option is disallowed if the publisher is running a version earlier
    3380                 :             :  * than the PG19, or if the publisher is in recovery (i.e., it is a standby
    3381                 :             :  * server).
    3382                 :             :  *
    3383                 :             :  * This is used both at DDL time (as a convenience, when a connection to the
    3384                 :             :  * publisher is already being made) and by the apply worker when it connects,
    3385                 :             :  * which is the authoritative check because the publisher's version and
    3386                 :             :  * recovery status can change after the DDL command.
    3387                 :             :  *
    3388                 :             :  * See comments atop worker.c for a detailed explanation.
    3389                 :             :  */
    3390                 :             : void
    3391                 :          19 : CheckPubDeadTupleRetention(WalReceiverConn *wrconn)
    3392                 :             : {
    3393                 :             :     WalRcvExecResult *res;
    3394                 :          19 :     Oid         RecoveryRow[1] = {BOOLOID};
    3395                 :             :     TupleTableSlot *slot;
    3396                 :             :     bool        isnull;
    3397                 :             :     bool        remote_in_recovery;
    3398                 :             : 
    3399         [ -  + ]:          19 :     if (walrcv_server_version(wrconn) < 190000)
    3400         [ #  # ]:           0 :         ereport(ERROR,
    3401                 :             :                 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    3402                 :             :                 errmsg("cannot enable retain_dead_tuples if the publisher is running a version earlier than PostgreSQL 19"));
    3403                 :             : 
    3404                 :          19 :     res = walrcv_exec(wrconn, "SELECT pg_is_in_recovery()", 1, RecoveryRow);
    3405                 :             : 
    3406         [ -  + ]:          19 :     if (res->status != WALRCV_OK_TUPLES)
    3407         [ #  # ]:           0 :         ereport(ERROR,
    3408                 :             :                 (errcode(ERRCODE_CONNECTION_FAILURE),
    3409                 :             :                  errmsg("could not obtain recovery progress from the publisher: %s",
    3410                 :             :                         res->err)));
    3411                 :             : 
    3412                 :          19 :     slot = MakeSingleTupleTableSlot(res->tupledesc, &TTSOpsMinimalTuple);
    3413         [ -  + ]:          19 :     if (!tuplestore_gettupleslot(res->tuplestore, true, false, slot))
    3414         [ #  # ]:           0 :         elog(ERROR, "failed to fetch tuple for the recovery progress");
    3415                 :             : 
    3416                 :          19 :     remote_in_recovery = DatumGetBool(slot_getattr(slot, 1, &isnull));
    3417                 :             : 
    3418         [ -  + ]:          19 :     if (remote_in_recovery)
    3419         [ #  # ]:           0 :         ereport(ERROR,
    3420                 :             :                 errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3421                 :             :                 errmsg("cannot enable retain_dead_tuples if the publisher is in recovery"));
    3422                 :             : 
    3423                 :          19 :     ExecDropSingleTupleTableSlot(slot);
    3424                 :             : 
    3425                 :          19 :     walrcv_clear_result(res);
    3426                 :          19 : }
    3427                 :             : 
    3428                 :             : /*
    3429                 :             :  * Check if the subscriber's configuration is adequate to enable the
    3430                 :             :  * retain_dead_tuples option.
    3431                 :             :  *
    3432                 :             :  * Issue an ERROR if the wal_level does not support the use of replication
    3433                 :             :  * slots when check_guc is set to true.
    3434                 :             :  *
    3435                 :             :  * Issue a WARNING if track_commit_timestamp is not enabled when check_guc is
    3436                 :             :  * set to true. This is only to highlight the importance of enabling
    3437                 :             :  * track_commit_timestamp instead of catching all the misconfigurations, as
    3438                 :             :  * this setting can be adjusted after subscription creation. Without it, the
    3439                 :             :  * apply worker will simply skip conflict detection.
    3440                 :             :  *
    3441                 :             :  * Issue a WARNING or NOTICE if the subscription is disabled and the retention
    3442                 :             :  * is active. Do not raise an ERROR since users can only modify
    3443                 :             :  * retain_dead_tuples for disabled subscriptions. And as long as the
    3444                 :             :  * subscription is enabled promptly, it will not pose issues.
    3445                 :             :  *
    3446                 :             :  * Issue a NOTICE to inform users that max_retention_duration is
    3447                 :             :  * ineffective when retain_dead_tuples is disabled for a subscription. An ERROR
    3448                 :             :  * is not issued because setting max_retention_duration causes no harm,
    3449                 :             :  * even when it is ineffective.
    3450                 :             :  */
    3451                 :             : void
    3452                 :         336 : CheckSubDeadTupleRetention(bool check_guc, bool sub_disabled,
    3453                 :             :                            int elevel_for_sub_disabled,
    3454                 :             :                            bool retain_dead_tuples, bool retention_active,
    3455                 :             :                            bool max_retention_set)
    3456                 :             : {
    3457                 :             :     Assert(elevel_for_sub_disabled == NOTICE ||
    3458                 :             :            elevel_for_sub_disabled == WARNING);
    3459                 :             : 
    3460         [ +  + ]:         336 :     if (retain_dead_tuples)
    3461                 :             :     {
    3462   [ +  +  -  + ]:          17 :         if (check_guc && wal_level < WAL_LEVEL_REPLICA)
    3463         [ #  # ]:           0 :             ereport(ERROR,
    3464                 :             :                     errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
    3465                 :             :                     errmsg("\"wal_level\" is insufficient to create the replication slot required by retain_dead_tuples"),
    3466                 :             :                     errhint("\"wal_level\" must be set to \"replica\" or \"logical\" at server start."));
    3467                 :             : 
    3468   [ +  +  +  + ]:          17 :         if (check_guc && !track_commit_timestamp)
    3469         [ +  - ]:           4 :             ereport(WARNING,
    3470                 :             :                     errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    3471                 :             :                     errmsg("commit timestamp and origin data required for detecting conflicts won't be retained"),
    3472                 :             :                     errhint("Consider setting \"%s\" to true.",
    3473                 :             :                             "track_commit_timestamp"));
    3474                 :             : 
    3475   [ +  +  +  - ]:          17 :         if (sub_disabled && retention_active)
    3476   [ +  -  +  + ]:           7 :             ereport(elevel_for_sub_disabled,
    3477                 :             :                     errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    3478                 :             :                     errmsg("deleted rows to detect conflicts would not be removed until the subscription is enabled"),
    3479                 :             :                     (elevel_for_sub_disabled > NOTICE)
    3480                 :             :                     ? errhint("Consider setting %s to false.",
    3481                 :             :                               "retain_dead_tuples") : 0);
    3482                 :             :     }
    3483         [ +  + ]:         319 :     else if (max_retention_set)
    3484                 :             :     {
    3485         [ +  - ]:           4 :         ereport(NOTICE,
    3486                 :             :                 errcode(ERRCODE_INVALID_PARAMETER_VALUE),
    3487                 :             :                 errmsg("max_retention_duration is ineffective when retain_dead_tuples is disabled"));
    3488                 :             :     }
    3489                 :         336 : }
    3490                 :             : 
    3491                 :             : /*
    3492                 :             :  * Return true iff 'rv' is a member of the list.
    3493                 :             :  */
    3494                 :             : static bool
    3495                 :         287 : list_member_rangevar(const List *list, RangeVar *rv)
    3496                 :             : {
    3497   [ +  +  +  +  :        1044 :     foreach_ptr(PublicationRelKind, relinfo, list)
                   +  + ]
    3498                 :             :     {
    3499         [ +  + ]:         472 :         if (equal(relinfo->rv, rv))
    3500                 :           1 :             return true;
    3501                 :             :     }
    3502                 :             : 
    3503                 :         286 :     return false;
    3504                 :             : }
    3505                 :             : 
    3506                 :             : /*
    3507                 :             :  * Get the list of tables and sequences which belong to specified publications
    3508                 :             :  * on the publisher connection.
    3509                 :             :  *
    3510                 :             :  * Note that we don't support the case where the column list is different for
    3511                 :             :  * the same table in different publications to avoid sending unwanted column
    3512                 :             :  * information for some of the rows. This can happen when both the column
    3513                 :             :  * list and row filter are specified for different publications.
    3514                 :             :  */
    3515                 :             : static List *
    3516                 :         164 : fetch_relation_list(WalReceiverConn *wrconn, List *publications)
    3517                 :             : {
    3518                 :             :     WalRcvExecResult *res;
    3519                 :             :     StringInfoData cmd;
    3520                 :             :     TupleTableSlot *slot;
    3521                 :         164 :     Oid         tableRow[4] = {TEXTOID, TEXTOID, CHAROID, InvalidOid};
    3522                 :         164 :     List       *relationlist = NIL;
    3523                 :         164 :     int         server_version = walrcv_server_version(wrconn);
    3524                 :         164 :     bool        check_columnlist = (server_version >= 150000);
    3525         [ +  - ]:         164 :     int         column_count = check_columnlist ? 4 : 3;
    3526                 :             :     StringInfoData pub_names;
    3527                 :             : 
    3528                 :         164 :     initStringInfo(&cmd);
    3529                 :         164 :     initStringInfo(&pub_names);
    3530                 :             : 
    3531                 :             :     /* Build the pub_names comma-separated string. */
    3532                 :         164 :     GetPublicationsStr(publications, &pub_names, true);
    3533                 :             : 
    3534                 :             :     /* Get the list of relations from the publisher */
    3535         [ +  - ]:         164 :     if (server_version >= 160000)
    3536                 :             :     {
    3537                 :         164 :         tableRow[3] = INT2VECTOROID;
    3538                 :             : 
    3539                 :             :         /*
    3540                 :             :          * From version 16, we allowed passing multiple publications to the
    3541                 :             :          * function pg_get_publication_tables. This helped to filter out the
    3542                 :             :          * partition table whose ancestor is also published in this
    3543                 :             :          * publication array.
    3544                 :             :          *
    3545                 :             :          * Join pg_get_publication_tables with pg_publication to exclude
    3546                 :             :          * non-existing publications.
    3547                 :             :          *
    3548                 :             :          * Note that attrs are always stored in sorted order so we don't need
    3549                 :             :          * to worry if different publications have specified them in a
    3550                 :             :          * different order. See pub_collist_validate.
    3551                 :             :          */
    3552                 :         164 :         appendStringInfo(&cmd, "SELECT DISTINCT n.nspname, c.relname, c.relkind, gpt.attrs\n"
    3553                 :             :                          "   FROM pg_class c\n"
    3554                 :             :                          "         JOIN pg_namespace n ON n.oid = c.relnamespace\n"
    3555                 :             :                          "         JOIN ( SELECT (pg_get_publication_tables(VARIADIC array_agg(pubname::text))).*\n"
    3556                 :             :                          "                FROM pg_publication\n"
    3557                 :             :                          "                WHERE pubname IN ( %s )) AS gpt\n"
    3558                 :             :                          "             ON gpt.relid = c.oid\n",
    3559                 :             :                          pub_names.data);
    3560                 :             : 
    3561                 :             :         /* From version 19, inclusion of sequences in the target is supported */
    3562         [ +  - ]:         164 :         if (server_version >= 190000)
    3563                 :         164 :             appendStringInfo(&cmd,
    3564                 :             :                              "UNION ALL\n"
    3565                 :             :                              "  SELECT DISTINCT s.schemaname, s.sequencename, " CppAsString2(RELKIND_SEQUENCE) "::\"char\" AS relkind, NULL::int2vector AS attrs\n"
    3566                 :             :                              "  FROM pg_catalog.pg_publication_sequences s\n"
    3567                 :             :                              "  WHERE s.pubname IN ( %s )",
    3568                 :             :                              pub_names.data);
    3569                 :             :     }
    3570                 :             :     else
    3571                 :             :     {
    3572                 :           0 :         tableRow[3] = NAMEARRAYOID;
    3573                 :           0 :         appendStringInfoString(&cmd, "SELECT DISTINCT t.schemaname, t.tablename, " CppAsString2(RELKIND_RELATION) "::\"char\" AS relkind \n");
    3574                 :             : 
    3575                 :             :         /* Get column lists for each relation if the publisher supports it */
    3576         [ #  # ]:           0 :         if (check_columnlist)
    3577                 :           0 :             appendStringInfoString(&cmd, ", t.attnames\n");
    3578                 :             : 
    3579                 :           0 :         appendStringInfo(&cmd, "FROM pg_catalog.pg_publication_tables t\n"
    3580                 :             :                          " WHERE t.pubname IN ( %s )",
    3581                 :             :                          pub_names.data);
    3582                 :             :     }
    3583                 :             : 
    3584                 :         164 :     pfree(pub_names.data);
    3585                 :             : 
    3586                 :         164 :     res = walrcv_exec(wrconn, cmd.data, column_count, tableRow);
    3587                 :         164 :     pfree(cmd.data);
    3588                 :             : 
    3589         [ -  + ]:         164 :     if (res->status != WALRCV_OK_TUPLES)
    3590         [ #  # ]:           0 :         ereport(ERROR,
    3591                 :             :                 (errcode(ERRCODE_CONNECTION_FAILURE),
    3592                 :             :                  errmsg("could not receive list of replicated tables from the publisher: %s",
    3593                 :             :                         res->err)));
    3594                 :             : 
    3595                 :             :     /* Process tables. */
    3596                 :         164 :     slot = MakeSingleTupleTableSlot(res->tupledesc, &TTSOpsMinimalTuple);
    3597         [ +  + ]:         467 :     while (tuplestore_gettupleslot(res->tuplestore, true, false, slot))
    3598                 :             :     {
    3599                 :             :         char       *nspname;
    3600                 :             :         char       *relname;
    3601                 :             :         bool        isnull;
    3602                 :             :         char        relkind;
    3603                 :         304 :         PublicationRelKind *relinfo = palloc_object(PublicationRelKind);
    3604                 :             : 
    3605                 :         304 :         nspname = TextDatumGetCString(slot_getattr(slot, 1, &isnull));
    3606                 :             :         Assert(!isnull);
    3607                 :         304 :         relname = TextDatumGetCString(slot_getattr(slot, 2, &isnull));
    3608                 :             :         Assert(!isnull);
    3609                 :         304 :         relkind = DatumGetChar(slot_getattr(slot, 3, &isnull));
    3610                 :             :         Assert(!isnull);
    3611                 :             : 
    3612                 :         304 :         relinfo->rv = makeRangeVar(nspname, relname, -1);
    3613                 :         304 :         relinfo->relkind = relkind;
    3614                 :             : 
    3615   [ +  +  +  - ]:         304 :         if (relkind != RELKIND_SEQUENCE &&
    3616         [ +  + ]:         287 :             check_columnlist &&
    3617                 :         287 :             list_member_rangevar(relationlist, relinfo->rv))
    3618         [ +  - ]:           1 :             ereport(ERROR,
    3619                 :             :                     errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    3620                 :             :                     errmsg("cannot use different column lists for table \"%s.%s\" in different publications",
    3621                 :             :                            nspname, relname));
    3622                 :             :         else
    3623                 :         303 :             relationlist = lappend(relationlist, relinfo);
    3624                 :             : 
    3625                 :         303 :         ExecClearTuple(slot);
    3626                 :             :     }
    3627                 :         163 :     ExecDropSingleTupleTableSlot(slot);
    3628                 :             : 
    3629                 :         163 :     walrcv_clear_result(res);
    3630                 :             : 
    3631                 :         163 :     return relationlist;
    3632                 :             : }
    3633                 :             : 
    3634                 :             : /*
    3635                 :             :  * This is to report the connection failure while dropping replication slots.
    3636                 :             :  * Here, we report the WARNING for all tablesync slots so that user can drop
    3637                 :             :  * them manually, if required.
    3638                 :             :  */
    3639                 :             : static void
    3640                 :           4 : ReportSlotConnectionError(List *rstates, Oid subid, char *slotname, char *err)
    3641                 :             : {
    3642                 :             :     ListCell   *lc;
    3643                 :             : 
    3644   [ -  +  -  -  :           4 :     foreach(lc, rstates)
                   -  + ]
    3645                 :             :     {
    3646                 :           0 :         SubscriptionRelState *rstate = (SubscriptionRelState *) lfirst(lc);
    3647                 :           0 :         Oid         relid = rstate->relid;
    3648                 :             : 
    3649                 :             :         /* Only cleanup resources of tablesync workers */
    3650         [ #  # ]:           0 :         if (!OidIsValid(relid))
    3651                 :           0 :             continue;
    3652                 :             : 
    3653                 :             :         /*
    3654                 :             :          * Caller needs to ensure that relstate doesn't change underneath us.
    3655                 :             :          * See DropSubscription where we get the relstates.
    3656                 :             :          */
    3657         [ #  # ]:           0 :         if (rstate->state != SUBREL_STATE_SYNCDONE)
    3658                 :             :         {
    3659                 :           0 :             char        syncslotname[NAMEDATALEN] = {0};
    3660                 :             : 
    3661                 :           0 :             ReplicationSlotNameForTablesync(subid, relid, syncslotname,
    3662                 :             :                                             sizeof(syncslotname));
    3663         [ #  # ]:           0 :             elog(WARNING, "could not drop tablesync replication slot \"%s\"",
    3664                 :             :                  syncslotname);
    3665                 :             :         }
    3666                 :             :     }
    3667                 :             : 
    3668         [ +  - ]:           4 :     ereport(ERROR,
    3669                 :             :             (errcode(ERRCODE_CONNECTION_FAILURE),
    3670                 :             :              errmsg("could not connect to publisher when attempting to drop replication slot \"%s\": %s",
    3671                 :             :                     slotname, err),
    3672                 :             :     /* translator: %s is an SQL ALTER command */
    3673                 :             :              errhint("Use %s to disable the subscription, and then use %s to disassociate it from the slot.",
    3674                 :             :                      "ALTER SUBSCRIPTION ... DISABLE",
    3675                 :             :                      "ALTER SUBSCRIPTION ... SET (slot_name = NONE)")));
    3676                 :             : }
    3677                 :             : 
    3678                 :             : /*
    3679                 :             :  * Check for duplicates in the given list of publications and error out if
    3680                 :             :  * found one.  Add publications to datums as text datums, if datums is not
    3681                 :             :  * NULL.
    3682                 :             :  */
    3683                 :             : static void
    3684                 :         290 : check_duplicates_in_publist(List *publist, Datum *datums)
    3685                 :             : {
    3686                 :             :     ListCell   *cell;
    3687                 :         290 :     int         j = 0;
    3688                 :             : 
    3689   [ +  -  +  +  :         654 :     foreach(cell, publist)
                   +  + ]
    3690                 :             :     {
    3691                 :         376 :         char       *name = strVal(lfirst(cell));
    3692                 :             :         ListCell   *pcell;
    3693                 :             : 
    3694   [ +  -  +  -  :         539 :         foreach(pcell, publist)
                   +  - ]
    3695                 :             :         {
    3696                 :         539 :             char       *pname = strVal(lfirst(pcell));
    3697                 :             : 
    3698         [ +  + ]:         539 :             if (pcell == cell)
    3699                 :         364 :                 break;
    3700                 :             : 
    3701         [ +  + ]:         175 :             if (strcmp(name, pname) == 0)
    3702         [ +  - ]:          12 :                 ereport(ERROR,
    3703                 :             :                         (errcode(ERRCODE_DUPLICATE_OBJECT),
    3704                 :             :                          errmsg("publication name \"%s\" used more than once",
    3705                 :             :                                 pname)));
    3706                 :             :         }
    3707                 :             : 
    3708         [ +  + ]:         364 :         if (datums)
    3709                 :         308 :             datums[j++] = CStringGetTextDatum(name);
    3710                 :             :     }
    3711                 :         278 : }
    3712                 :             : 
    3713                 :             : /*
    3714                 :             :  * Merge current subscription's publications and user-specified publications
    3715                 :             :  * from ADD/DROP PUBLICATIONS.
    3716                 :             :  *
    3717                 :             :  * If addpub is true, we will add the list of publications into oldpublist.
    3718                 :             :  * Otherwise, we will delete the list of publications from oldpublist.  The
    3719                 :             :  * returned list is a copy, oldpublist itself is not changed.
    3720                 :             :  *
    3721                 :             :  * subname is the subscription name, for error messages.
    3722                 :             :  */
    3723                 :             : static List *
    3724                 :          35 : merge_publications(List *oldpublist, List *newpublist, bool addpub, const char *subname)
    3725                 :             : {
    3726                 :             :     ListCell   *lc;
    3727                 :             : 
    3728                 :          35 :     oldpublist = list_copy(oldpublist);
    3729                 :             : 
    3730                 :          35 :     check_duplicates_in_publist(newpublist, NULL);
    3731                 :             : 
    3732   [ +  -  +  +  :          59 :     foreach(lc, newpublist)
                   +  + ]
    3733                 :             :     {
    3734                 :          44 :         char       *name = strVal(lfirst(lc));
    3735                 :             :         ListCell   *lc2;
    3736                 :          44 :         bool        found = false;
    3737                 :             : 
    3738   [ +  -  +  +  :          86 :         foreach(lc2, oldpublist)
                   +  + ]
    3739                 :             :         {
    3740                 :          71 :             char       *pubname = strVal(lfirst(lc2));
    3741                 :             : 
    3742         [ +  + ]:          71 :             if (strcmp(name, pubname) == 0)
    3743                 :             :             {
    3744                 :          29 :                 found = true;
    3745         [ +  + ]:          29 :                 if (addpub)
    3746         [ +  - ]:           8 :                     ereport(ERROR,
    3747                 :             :                             (errcode(ERRCODE_DUPLICATE_OBJECT),
    3748                 :             :                              errmsg("publication \"%s\" is already in subscription \"%s\"",
    3749                 :             :                                     name, subname)));
    3750                 :             :                 else
    3751                 :          21 :                     oldpublist = foreach_delete_current(oldpublist, lc2);
    3752                 :             : 
    3753                 :          21 :                 break;
    3754                 :             :             }
    3755                 :             :         }
    3756                 :             : 
    3757   [ +  +  +  - ]:          36 :         if (addpub && !found)
    3758                 :          11 :             oldpublist = lappend(oldpublist, makeString(name));
    3759   [ +  -  +  + ]:          25 :         else if (!addpub && !found)
    3760         [ +  - ]:           4 :             ereport(ERROR,
    3761                 :             :                     (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    3762                 :             :                      errmsg("publication \"%s\" is not in subscription \"%s\"",
    3763                 :             :                             name, subname)));
    3764                 :             :     }
    3765                 :             : 
    3766                 :             :     /*
    3767                 :             :      * XXX Probably no strong reason for this, but for now it's to make ALTER
    3768                 :             :      * SUBSCRIPTION ... DROP PUBLICATION consistent with SET PUBLICATION.
    3769                 :             :      */
    3770         [ +  + ]:          15 :     if (!oldpublist)
    3771         [ +  - ]:           4 :         ereport(ERROR,
    3772                 :             :                 (errcode(ERRCODE_INVALID_OBJECT_DEFINITION),
    3773                 :             :                  errmsg("cannot drop all the publications from a subscription")));
    3774                 :             : 
    3775                 :          11 :     return oldpublist;
    3776                 :             : }
    3777                 :             : 
    3778                 :             : /*
    3779                 :             :  * Extract the streaming mode value from a DefElem.  This is like
    3780                 :             :  * defGetBoolean() but also accepts the special value of "parallel".
    3781                 :             :  */
    3782                 :             : char
    3783                 :         478 : defGetStreamingMode(DefElem *def)
    3784                 :             : {
    3785                 :             :     /*
    3786                 :             :      * If no parameter value given, assume "true" is meant.
    3787                 :             :      */
    3788         [ -  + ]:         478 :     if (!def->arg)
    3789                 :           0 :         return LOGICALREP_STREAM_ON;
    3790                 :             : 
    3791                 :             :     /*
    3792                 :             :      * Allow 0, 1, "false", "true", "off", "on" or "parallel".
    3793                 :             :      */
    3794         [ -  + ]:         478 :     switch (nodeTag(def->arg))
    3795                 :             :     {
    3796                 :           0 :         case T_Integer:
    3797      [ #  #  # ]:           0 :             switch (intVal(def->arg))
    3798                 :             :             {
    3799                 :           0 :                 case 0:
    3800                 :           0 :                     return LOGICALREP_STREAM_OFF;
    3801                 :           0 :                 case 1:
    3802                 :           0 :                     return LOGICALREP_STREAM_ON;
    3803                 :           0 :                 default:
    3804                 :             :                     /* otherwise, error out below */
    3805                 :           0 :                     break;
    3806                 :             :             }
    3807                 :           0 :             break;
    3808                 :         478 :         default:
    3809                 :             :             {
    3810                 :         478 :                 char       *sval = defGetString(def);
    3811                 :             : 
    3812                 :             :                 /*
    3813                 :             :                  * The set of strings accepted here should match up with the
    3814                 :             :                  * grammar's opt_boolean_or_string production.
    3815                 :             :                  */
    3816   [ +  +  +  + ]:         952 :                 if (pg_strcasecmp(sval, "false") == 0 ||
    3817                 :         474 :                     pg_strcasecmp(sval, "off") == 0)
    3818                 :           7 :                     return LOGICALREP_STREAM_OFF;
    3819   [ +  +  +  + ]:         930 :                 if (pg_strcasecmp(sval, "true") == 0 ||
    3820                 :         459 :                     pg_strcasecmp(sval, "on") == 0)
    3821                 :          48 :                     return LOGICALREP_STREAM_ON;
    3822         [ +  + ]:         423 :                 if (pg_strcasecmp(sval, "parallel") == 0)
    3823                 :         419 :                     return LOGICALREP_STREAM_PARALLEL;
    3824                 :             :             }
    3825                 :           4 :             break;
    3826                 :             :     }
    3827                 :             : 
    3828         [ +  - ]:           4 :     ereport(ERROR,
    3829                 :             :             (errcode(ERRCODE_SYNTAX_ERROR),
    3830                 :             :              errmsg("%s requires a Boolean value or \"parallel\"",
    3831                 :             :                     def->defname)));
    3832                 :             :     return LOGICALREP_STREAM_OFF;   /* keep compiler quiet */
    3833                 :             : }
        

Generated by: LCOV version 2.0-1