LCOV - differential code coverage report
Current view: top level - src/backend/commands - subscriptioncmds.c (source / functions) Coverage Total Hit UNC UBC GNC CBC DCB
Current: ba12a202ce1b5581dc0ed149cf3f637d7897ad5d vs 2866d8c7dbfc9d882a7d80fef93fbbe763709932 Lines: 90.9 % 1272 1156 2 114 63 1093 3
Current Date: 2026-08-27 14:31:44 +0300 Functions: 100.0 % 27 27 8 19
Baseline: lcov-20260827-baseline Branches: 72.4 % 1114 807 6 301 38 769
Baseline Date: 2026-08-27 14:31:58 +0300 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
[..1] days: 58.8 % 17 10 7 10
(7,30] days: 96.9 % 65 63 2 3 60
(30,360] days: 93.5 % 400 374 2 24 60 314
(360..) days: 89.7 % 790 709 81 709
Function coverage date bins:
(7,30] days: 100.0 % 2 2 2
(30,360] days: 100.0 % 8 8 2 6
(360..) days: 100.0 % 17 17 6 11
Branch coverage date bins:
[..1] days: 37.5 % 8 3 5 3
(7,30] days: 71.0 % 62 44 18 44
(30,360] days: 76.1 % 293 223 6 64 38 185
(360..) days: 71.5 % 751 537 214 537

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

Generated by: LCOV version 2.0-1