LCOV - differential code coverage report
Current view: top level - src/backend/commands - subscriptioncmds.c (source / functions) Coverage Total Hit UNC UBC GBC GNC CBC DCB
Current: Differential Code Coverage 16@8cea358b128 vs 17@8cea358b128 Lines: 87.8 % 833 731 4 98 1 35 695 6
Current Date: 2024-04-14 14:21:10 Functions: 88.9 % 18 16 2 6 10
Baseline: 16@8cea358b128 Branches: 69.5 % 725 504 17 204 4 31 469
Baseline Date: 2024-04-14 14:21:09 Line coverage date bins:
Legend: Lines: hit not hit | Branches: + taken - not taken # not executed [..60] days: 100.0 % 1 1 1
(60,120] days: 89.2 % 37 33 4 33
(120,180] days: 100.0 % 1 1 1
(180,240] days: 100.0 % 4 4 4
(240..) days: 87.6 % 790 692 98 1 691
Function coverage date bins:
(240..) days: 88.9 % 18 16 2 6 10
Branch coverage date bins:
(60,120] days: 63.6 % 44 28 16 28
(120,180] days: 75.0 % 4 3 1 3
(180,240] days: 100.0 % 2 2 2
(240..) days: 69.8 % 675 471 204 4 467

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

Generated by: LCOV version 2.1-beta2-3-g6141622