LCOV - differential code coverage report
Current view: top level - src/backend/commands - subscriptioncmds.c (source / functions) Coverage Total Hit UNC UIC UBC GBC GIC GNC CBC DCB
Current: 4b3c9325757dfd8f2312e9f1a8decf4431f344ae vs e87b024bfb8dd55e3049b1b6e6ab4e810cf1abc8 Lines: 91.0 % 1301 1184 4 113 90 1094 5
Current Date: 2026-11-28 16:48:44 +0900 Functions: 100.0 % 27 27 9 18
Baseline: lcov-20261128-baseline Branches: 73.1 % 1156 845 17 1 293 1 1 67 776
Baseline Date: 2026-11-28 16:48:48 +0900 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(1,7] days: 94.1 % 34 32 2 31 1
(7,30] days: 100.0 % 9 9 9
(30,360] days: 93.9 % 293 275 2 16 59 216
(360..) days: 89.9 % 965 868 97 868
Function coverage date bins:
(1,7] days: 100.0 % 1 1 1
(30,360] days: 100.0 % 5 5 1 4
(360..) days: 100.0 % 21 21 7 14
Branch coverage date bins:
(1,7] days: 72.5 % 40 29 11 29
(7,30] days: 100.0 % 6 6 6
(30,360] days: 75.1 % 221 166 6 49 38 128
(360..) days: 72.4 % 889 644 1 244 1 1 642

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

Generated by: LCOV version 2.0-1