LCOV - differential code coverage report
Current view: top level - src/backend/commands - subscriptioncmds.c (source / functions) Coverage Total Hit UNC LBC UIC UBC GBC GIC GNC CBC DUB DCB
Current: bed3ffbf9d952be6c7d739d068cdce44c046dfb7 vs 574581b50ac9c63dd9e4abebb731a3b67e5b50f6 Lines: 88.6 % 1110 984 38 1 87 5 327 652 4 86
Current Date: 2026-05-05 10:23:31 +0900 Functions: 95.7 % 23 22 1 1 17 4 2
Baseline: lcov-20260505-025707-baseline Branches: 71.1 % 987 702 86 2 2 195 9 2 228 463 9 55
Baseline Date: 2026-05-05 10:27:06 +0900 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(1,7] days: 100.0 % 1 1 1
(7,30] days: 100.0 % 3 3 3
(30,360] days: 89.3 % 363 324 38 1 320 4
(360..) days: 88.3 % 743 656 87 5 3 648
Function coverage date bins:
(30,360] days: 100.0 % 7 7 7
(360..) days: 93.8 % 16 15 1 1 10 4
Branch coverage date bins:
(30,360] days: 71.8 % 316 227 86 2 1 226 1
(360..) days: 70.8 % 671 475 2 194 9 2 2 462

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

Generated by: LCOV version 2.5.0-beta