LCOV - code coverage report
Current view: top level - src/backend/replication/logical - tablesync.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 91.0 % 489 445
Test Date: 2026-11-29 06:16:37 Functions: 100.0 % 16 16
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 67.8 % 258 175

             Branch data     Line data    Source code
       1                 :             : /*-------------------------------------------------------------------------
       2                 :             :  * tablesync.c
       3                 :             :  *    PostgreSQL logical replication: initial table data synchronization
       4                 :             :  *
       5                 :             :  * Copyright (c) 2012-2026, PostgreSQL Global Development Group
       6                 :             :  *
       7                 :             :  * IDENTIFICATION
       8                 :             :  *    src/backend/replication/logical/tablesync.c
       9                 :             :  *
      10                 :             :  * NOTES
      11                 :             :  *    This file contains code for initial table data synchronization for
      12                 :             :  *    logical replication.
      13                 :             :  *
      14                 :             :  *    The initial data synchronization is done separately for each table,
      15                 :             :  *    in a separate apply worker that only fetches the initial snapshot data
      16                 :             :  *    from the publisher and then synchronizes the position in the stream with
      17                 :             :  *    the leader apply worker.
      18                 :             :  *
      19                 :             :  *    There are several reasons for doing the synchronization this way:
      20                 :             :  *     - It allows us to parallelize the initial data synchronization
      21                 :             :  *       which lowers the time needed for it to happen.
      22                 :             :  *     - The initial synchronization does not have to hold the xid and LSN
      23                 :             :  *       for the time it takes to copy data of all tables, causing less
      24                 :             :  *       bloat and lower disk consumption compared to doing the
      25                 :             :  *       synchronization in a single process for the whole database.
      26                 :             :  *     - It allows us to synchronize any tables added after the initial
      27                 :             :  *       synchronization has finished.
      28                 :             :  *
      29                 :             :  *    The stream position synchronization works in multiple steps:
      30                 :             :  *     - Apply worker requests a tablesync worker to start, setting the new
      31                 :             :  *       table state to INIT.
      32                 :             :  *     - Tablesync worker starts; changes table state from INIT to DATASYNC while
      33                 :             :  *       copying.
      34                 :             :  *     - Tablesync worker does initial table copy; there is a FINISHEDCOPY (sync
      35                 :             :  *       worker specific) state to indicate when the copy phase has completed, so
      36                 :             :  *       if the worker crashes with this (non-memory) state then the copy will not
      37                 :             :  *       be re-attempted.
      38                 :             :  *     - Tablesync worker then sets table state to SYNCWAIT; waits for state change.
      39                 :             :  *     - Apply worker periodically checks for tables in SYNCWAIT state.  When
      40                 :             :  *       any appear, it sets the table state to CATCHUP and starts loop-waiting
      41                 :             :  *       until either the table state is set to SYNCDONE or the sync worker
      42                 :             :  *       exits.
      43                 :             :  *     - After the sync worker has seen the state change to CATCHUP, it will
      44                 :             :  *       read the stream and apply changes (acting like an apply worker) until
      45                 :             :  *       it catches up to the specified stream position.  Then it sets the
      46                 :             :  *       state to SYNCDONE.  There might be zero changes applied between
      47                 :             :  *       CATCHUP and SYNCDONE, because the sync worker might be ahead of the
      48                 :             :  *       apply worker.
      49                 :             :  *     - Once the state is set to SYNCDONE, the apply will continue tracking
      50                 :             :  *       the table until it reaches the SYNCDONE stream position, at which
      51                 :             :  *       point it sets state to READY and stops tracking.  Again, there might
      52                 :             :  *       be zero changes in between.
      53                 :             :  *
      54                 :             :  *    So the state progression is always: INIT -> DATASYNC -> FINISHEDCOPY
      55                 :             :  *    -> SYNCWAIT -> CATCHUP -> SYNCDONE -> READY.
      56                 :             :  *
      57                 :             :  *    The catalog pg_subscription_rel is used to keep information about
      58                 :             :  *    subscribed tables and their state.  The catalog holds all states
      59                 :             :  *    except SYNCWAIT and CATCHUP which are only in shared memory.
      60                 :             :  *
      61                 :             :  *    Example flows look like this:
      62                 :             :  *     - Apply is in front:
      63                 :             :  *        sync:8
      64                 :             :  *          -> set in catalog FINISHEDCOPY
      65                 :             :  *          -> set in memory SYNCWAIT
      66                 :             :  *        apply:10
      67                 :             :  *          -> set in memory CATCHUP
      68                 :             :  *          -> enter wait-loop
      69                 :             :  *        sync:10
      70                 :             :  *          -> set in catalog SYNCDONE
      71                 :             :  *          -> exit
      72                 :             :  *        apply:10
      73                 :             :  *          -> exit wait-loop
      74                 :             :  *          -> continue rep
      75                 :             :  *        apply:11
      76                 :             :  *          -> set in catalog READY
      77                 :             :  *
      78                 :             :  *     - Sync is in front:
      79                 :             :  *        sync:10
      80                 :             :  *          -> set in catalog FINISHEDCOPY
      81                 :             :  *          -> set in memory SYNCWAIT
      82                 :             :  *        apply:8
      83                 :             :  *          -> set in memory CATCHUP
      84                 :             :  *          -> continue per-table filtering
      85                 :             :  *        sync:10
      86                 :             :  *          -> set in catalog SYNCDONE
      87                 :             :  *          -> exit
      88                 :             :  *        apply:10
      89                 :             :  *          -> set in catalog READY
      90                 :             :  *          -> stop per-table filtering
      91                 :             :  *          -> continue rep
      92                 :             :  *-------------------------------------------------------------------------
      93                 :             :  */
      94                 :             : 
      95                 :             : #include "postgres.h"
      96                 :             : 
      97                 :             : #include "access/table.h"
      98                 :             : #include "access/xact.h"
      99                 :             : #include "catalog/indexing.h"
     100                 :             : #include "catalog/pg_subscription_rel.h"
     101                 :             : #include "catalog/pg_type.h"
     102                 :             : #include "commands/copy.h"
     103                 :             : #include "miscadmin.h"
     104                 :             : #include "nodes/makefuncs.h"
     105                 :             : #include "parser/parse_relation.h"
     106                 :             : #include "pgstat.h"
     107                 :             : #include "replication/logicallauncher.h"
     108                 :             : #include "replication/logicalrelation.h"
     109                 :             : #include "replication/logicalworker.h"
     110                 :             : #include "replication/origin.h"
     111                 :             : #include "replication/slot.h"
     112                 :             : #include "replication/walreceiver.h"
     113                 :             : #include "replication/worker_internal.h"
     114                 :             : #include "storage/ipc.h"
     115                 :             : #include "storage/latch.h"
     116                 :             : #include "storage/lmgr.h"
     117                 :             : #include "utils/acl.h"
     118                 :             : #include "utils/array.h"
     119                 :             : #include "utils/builtins.h"
     120                 :             : #include "utils/lsyscache.h"
     121                 :             : #include "utils/rls.h"
     122                 :             : #include "utils/snapmgr.h"
     123                 :             : #include "utils/syscache.h"
     124                 :             : #include "utils/usercontext.h"
     125                 :             : #include "utils/wait_event.h"
     126                 :             : 
     127                 :             : List       *table_states_not_ready = NIL;
     128                 :             : 
     129                 :             : /*
     130                 :             :  * Wait until the relation sync state is set in the catalog to the expected
     131                 :             :  * one; return true when it happens.
     132                 :             :  *
     133                 :             :  * Returns false if the table sync worker or the table itself have
     134                 :             :  * disappeared, or the table state has been reset.
     135                 :             :  *
     136                 :             :  * Currently, this is used in the apply worker when transitioning from
     137                 :             :  * CATCHUP state to SYNCDONE.
     138                 :             :  */
     139                 :             : static bool
     140                 :         207 : wait_for_table_state_change(Oid relid, char expected_state)
     141                 :             : {
     142                 :             :     char        state;
     143                 :             : 
     144                 :             :     for (;;)
     145                 :         221 :     {
     146                 :             :         LogicalRepWorker *worker;
     147                 :             :         XLogRecPtr  statelsn;
     148                 :             : 
     149         [ -  + ]:         428 :         CHECK_FOR_INTERRUPTS();
     150                 :             : 
     151                 :         428 :         InvalidateCatalogSnapshot();
     152                 :         428 :         state = GetSubscriptionRelState(MyLogicalRepWorker->subid,
     153                 :             :                                         relid, &statelsn);
     154                 :             : 
     155         [ -  + ]:         428 :         if (state == SUBREL_STATE_UNKNOWN)
     156                 :           0 :             break;
     157                 :             : 
     158         [ +  + ]:         428 :         if (state == expected_state)
     159                 :         207 :             return true;
     160                 :             : 
     161                 :             :         /* Check if the sync worker is still running and bail if not. */
     162                 :         221 :         LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
     163                 :         221 :         worker = logicalrep_worker_find(WORKERTYPE_TABLESYNC,
     164                 :         221 :                                         MyLogicalRepWorker->subid, relid,
     165                 :             :                                         false);
     166                 :         221 :         LWLockRelease(LogicalRepWorkerLock);
     167         [ -  + ]:         221 :         if (!worker)
     168                 :           0 :             break;
     169                 :             : 
     170                 :         221 :         (void) WaitLatch(MyLatch,
     171                 :             :                          WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH,
     172                 :             :                          1000L, WAIT_EVENT_LOGICAL_SYNC_STATE_CHANGE);
     173                 :             : 
     174                 :         221 :         ResetLatch(MyLatch);
     175                 :             :     }
     176                 :             : 
     177                 :           0 :     return false;
     178                 :             : }
     179                 :             : 
     180                 :             : /*
     181                 :             :  * Wait until the apply worker changes the state of our synchronization
     182                 :             :  * worker to the expected one.
     183                 :             :  *
     184                 :             :  * Used when transitioning from SYNCWAIT state to CATCHUP.
     185                 :             :  *
     186                 :             :  * Returns false if the apply worker has disappeared.
     187                 :             :  */
     188                 :             : static bool
     189                 :         209 : wait_for_worker_state_change(char expected_state)
     190                 :             : {
     191                 :             :     int         rc;
     192                 :             : 
     193                 :             :     for (;;)
     194                 :         209 :     {
     195                 :             :         LogicalRepWorker *worker;
     196                 :             : 
     197         [ -  + ]:         418 :         CHECK_FOR_INTERRUPTS();
     198                 :             : 
     199                 :             :         /*
     200                 :             :          * Done if already in correct state.  (We assume this fetch is atomic
     201                 :             :          * enough to not give a misleading answer if we do it with no lock.)
     202                 :             :          */
     203         [ +  + ]:         418 :         if (MyLogicalRepWorker->relstate == expected_state)
     204                 :         209 :             return true;
     205                 :             : 
     206                 :             :         /*
     207                 :             :          * Bail out if the apply worker has died, else signal it we're
     208                 :             :          * waiting.
     209                 :             :          */
     210                 :         209 :         LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
     211                 :         209 :         worker = logicalrep_worker_find(WORKERTYPE_APPLY,
     212                 :         209 :                                         MyLogicalRepWorker->subid, InvalidOid,
     213                 :             :                                         false);
     214   [ +  -  +  - ]:         209 :         if (worker && worker->proc)
     215                 :         209 :             logicalrep_worker_wakeup_ptr(worker);
     216                 :         209 :         LWLockRelease(LogicalRepWorkerLock);
     217         [ -  + ]:         209 :         if (!worker)
     218                 :           0 :             break;
     219                 :             : 
     220                 :             :         /*
     221                 :             :          * Wait.  We expect to get a latch signal back from the apply worker,
     222                 :             :          * but use a timeout in case it dies without sending one.
     223                 :             :          */
     224                 :         209 :         rc = WaitLatch(MyLatch,
     225                 :             :                        WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH,
     226                 :             :                        1000L, WAIT_EVENT_LOGICAL_SYNC_STATE_CHANGE);
     227                 :             : 
     228         [ +  - ]:         209 :         if (rc & WL_LATCH_SET)
     229                 :         209 :             ResetLatch(MyLatch);
     230                 :             :     }
     231                 :             : 
     232                 :           0 :     return false;
     233                 :             : }
     234                 :             : 
     235                 :             : /*
     236                 :             :  * Handle table synchronization cooperation from the synchronization
     237                 :             :  * worker.
     238                 :             :  *
     239                 :             :  * If the sync worker is in CATCHUP state and reached (or passed) the
     240                 :             :  * predetermined synchronization point in the WAL stream, mark the table as
     241                 :             :  * SYNCDONE and finish.
     242                 :             :  */
     243                 :             : void
     244                 :         234 : ProcessSyncingTablesForSync(XLogRecPtr current_lsn)
     245                 :             : {
     246                 :         234 :     SpinLockAcquire(&MyLogicalRepWorker->relmutex);
     247                 :             : 
     248         [ +  - ]:         234 :     if (MyLogicalRepWorker->relstate == SUBREL_STATE_CATCHUP &&
     249         [ +  + ]:         234 :         current_lsn >= MyLogicalRepWorker->relstate_lsn)
     250                 :             :     {
     251                 :             :         TimeLineID  tli;
     252                 :         209 :         char        syncslotname[NAMEDATALEN] = {0};
     253                 :         209 :         char        originname[NAMEDATALEN] = {0};
     254                 :             : 
     255                 :         209 :         MyLogicalRepWorker->relstate = SUBREL_STATE_SYNCDONE;
     256                 :         209 :         MyLogicalRepWorker->relstate_lsn = current_lsn;
     257                 :             : 
     258                 :         209 :         SpinLockRelease(&MyLogicalRepWorker->relmutex);
     259                 :             : 
     260                 :             :         /*
     261                 :             :          * UpdateSubscriptionRelState must be called within a transaction.
     262                 :             :          */
     263         [ +  - ]:         209 :         if (!IsTransactionState())
     264                 :         209 :             StartTransactionCommand();
     265                 :             : 
     266                 :         209 :         UpdateSubscriptionRelState(MyLogicalRepWorker->subid,
     267                 :         209 :                                    MyLogicalRepWorker->relid,
     268                 :         209 :                                    MyLogicalRepWorker->relstate,
     269                 :         209 :                                    MyLogicalRepWorker->relstate_lsn,
     270                 :             :                                    false);
     271                 :             : 
     272                 :             :         /*
     273                 :             :          * End streaming so that LogRepWorkerWalRcvConn can be used to drop
     274                 :             :          * the slot.
     275                 :             :          */
     276                 :         209 :         walrcv_endstreaming(LogRepWorkerWalRcvConn, &tli);
     277                 :             : 
     278                 :             :         /*
     279                 :             :          * Cleanup the tablesync slot.
     280                 :             :          *
     281                 :             :          * This has to be done after updating the state because otherwise if
     282                 :             :          * there is an error while doing the database operations we won't be
     283                 :             :          * able to rollback dropped slot.
     284                 :             :          */
     285                 :         209 :         ReplicationSlotNameForTablesync(MyLogicalRepWorker->subid,
     286                 :         209 :                                         MyLogicalRepWorker->relid,
     287                 :             :                                         syncslotname,
     288                 :             :                                         sizeof(syncslotname));
     289                 :             : 
     290                 :             :         /*
     291                 :             :          * It is important to give an error if we are unable to drop the slot,
     292                 :             :          * otherwise, it won't be dropped till the corresponding subscription
     293                 :             :          * is dropped. So passing missing_ok = false.
     294                 :             :          */
     295                 :         209 :         ReplicationSlotDropAtPubNode(LogRepWorkerWalRcvConn, syncslotname, false);
     296                 :             : 
     297                 :         209 :         CommitTransactionCommand();
     298                 :         209 :         pgstat_report_stat(false);
     299                 :             : 
     300                 :             :         /*
     301                 :             :          * Start a new transaction to clean up the tablesync origin tracking.
     302                 :             :          * This transaction will be ended within the FinishSyncWorker(). Now,
     303                 :             :          * even, if we fail to remove this here, the apply worker will ensure
     304                 :             :          * to clean it up afterward.
     305                 :             :          *
     306                 :             :          * We need to do this after the table state is set to SYNCDONE.
     307                 :             :          * Otherwise, if an error occurs while performing the database
     308                 :             :          * operation, the worker will be restarted and the in-memory state of
     309                 :             :          * replication progress (remote_lsn) won't be rolled-back which would
     310                 :             :          * have been cleared before restart. So, the restarted worker will use
     311                 :             :          * invalid replication progress state resulting in replay of
     312                 :             :          * transactions that have already been applied.
     313                 :             :          */
     314                 :         209 :         StartTransactionCommand();
     315                 :             : 
     316                 :         209 :         ReplicationOriginNameForLogicalRep(MyLogicalRepWorker->subid,
     317                 :         209 :                                            MyLogicalRepWorker->relid,
     318                 :             :                                            originname,
     319                 :             :                                            sizeof(originname));
     320                 :             : 
     321                 :             :         /*
     322                 :             :          * Resetting the origin session removes the ownership of the slot.
     323                 :             :          * This is needed to allow the origin to be dropped.
     324                 :             :          */
     325                 :         209 :         replorigin_session_reset();
     326                 :         209 :         replorigin_xact_clear(true);
     327                 :             : 
     328                 :             :         /*
     329                 :             :          * Drop the tablesync's origin tracking if exists.
     330                 :             :          *
     331                 :             :          * There is a chance that the user is concurrently performing refresh
     332                 :             :          * for the subscription where we remove the table state and its origin
     333                 :             :          * or the apply worker would have removed this origin. So passing
     334                 :             :          * missing_ok = true.
     335                 :             :          */
     336                 :         209 :         replorigin_drop_by_name(originname, true, false);
     337                 :             : 
     338                 :         209 :         FinishSyncWorker();
     339                 :             :     }
     340                 :             :     else
     341                 :          25 :         SpinLockRelease(&MyLogicalRepWorker->relmutex);
     342                 :          25 : }
     343                 :             : 
     344                 :             : /*
     345                 :             :  * Handle table synchronization cooperation from the apply worker.
     346                 :             :  *
     347                 :             :  * Walk over all subscription tables that are individually tracked by the
     348                 :             :  * apply process (currently, all that have state other than
     349                 :             :  * SUBREL_STATE_READY) and manage synchronization for them.
     350                 :             :  *
     351                 :             :  * If there are tables that need synchronizing and are not being synchronized
     352                 :             :  * yet, start sync workers for them (if there are free slots for sync
     353                 :             :  * workers).  To prevent starting the sync worker for the same relation at a
     354                 :             :  * high frequency after a failure, we store its last start time with each sync
     355                 :             :  * state info.  We start the sync worker for the same relation after waiting
     356                 :             :  * at least wal_retrieve_retry_interval.
     357                 :             :  *
     358                 :             :  * For tables that are being synchronized already, check if sync workers
     359                 :             :  * either need action from the apply worker or have finished.  This is the
     360                 :             :  * SYNCWAIT to CATCHUP transition.
     361                 :             :  *
     362                 :             :  * If the synchronization position is reached (SYNCDONE), then the table can
     363                 :             :  * be marked as READY and is no longer tracked.
     364                 :             :  */
     365                 :             : void
     366                 :        7025 : ProcessSyncingTablesForApply(XLogRecPtr current_lsn)
     367                 :             : {
     368                 :             :     struct tablesync_start_time_mapping
     369                 :             :     {
     370                 :             :         Oid         relid;
     371                 :             :         TimestampTz last_start_time;
     372                 :             :     };
     373                 :             :     static HTAB *last_start_times = NULL;
     374                 :             :     ListCell   *lc;
     375                 :             :     bool        started_tx;
     376                 :        7025 :     bool        should_exit = false;
     377                 :        7025 :     Relation    rel = NULL;
     378                 :             : 
     379                 :             :     Assert(!IsTransactionState());
     380                 :             : 
     381                 :             :     /* We need up-to-date sync state info for subscription tables here. */
     382                 :        7025 :     FetchRelationStates(NULL, NULL, &started_tx);
     383                 :             : 
     384                 :             :     /*
     385                 :             :      * Prepare a hash table for tracking last start times of workers, to avoid
     386                 :             :      * immediate restarts.  We don't need it if there are no tables that need
     387                 :             :      * syncing.
     388                 :             :      */
     389   [ +  +  +  + ]:        7025 :     if (table_states_not_ready != NIL && !last_start_times)
     390                 :         136 :     {
     391                 :             :         HASHCTL     ctl;
     392                 :             : 
     393                 :         136 :         ctl.keysize = sizeof(Oid);
     394                 :         136 :         ctl.entrysize = sizeof(struct tablesync_start_time_mapping);
     395                 :         136 :         last_start_times = hash_create("Logical replication table sync worker start times",
     396                 :             :                                        256, &ctl, HASH_ELEM | HASH_BLOBS);
     397                 :             :     }
     398                 :             : 
     399                 :             :     /*
     400                 :             :      * Clean up the hash table when we're done with all tables (just to
     401                 :             :      * release the bit of memory).
     402                 :             :      */
     403   [ +  +  +  + ]:        6889 :     else if (table_states_not_ready == NIL && last_start_times)
     404                 :             :     {
     405                 :         106 :         hash_destroy(last_start_times);
     406                 :         106 :         last_start_times = NULL;
     407                 :             :     }
     408                 :             : 
     409                 :             :     /*
     410                 :             :      * Process all tables that are being synchronized.
     411                 :             :      */
     412   [ +  +  +  +  :        8929 :     foreach(lc, table_states_not_ready)
                   +  + ]
     413                 :             :     {
     414                 :        1905 :         SubscriptionRelState *rstate = (SubscriptionRelState *) lfirst(lc);
     415                 :             : 
     416         [ +  + ]:        1905 :         if (!started_tx)
     417                 :             :         {
     418                 :         338 :             StartTransactionCommand();
     419                 :         338 :             started_tx = true;
     420                 :             :         }
     421                 :             : 
     422                 :             :         Assert(get_rel_relkind(rstate->relid) != RELKIND_SEQUENCE);
     423                 :             : 
     424         [ +  + ]:        1905 :         if (rstate->state == SUBREL_STATE_SYNCDONE)
     425                 :             :         {
     426                 :             :             /*
     427                 :             :              * Apply has caught up to the position where the table sync has
     428                 :             :              * finished.  Mark the table as ready so that the apply will just
     429                 :             :              * continue to replicate it normally.
     430                 :             :              */
     431         [ +  - ]:         206 :             if (current_lsn >= rstate->lsn)
     432                 :             :             {
     433                 :             :                 char        originname[NAMEDATALEN];
     434                 :             : 
     435                 :         206 :                 rstate->state = SUBREL_STATE_READY;
     436                 :         206 :                 rstate->lsn = current_lsn;
     437                 :             : 
     438                 :             :                 /*
     439                 :             :                  * Remove the tablesync origin tracking if exists.
     440                 :             :                  *
     441                 :             :                  * There is a chance that the user is concurrently performing
     442                 :             :                  * refresh for the subscription where we remove the table
     443                 :             :                  * state and its origin or the tablesync worker would have
     444                 :             :                  * already removed this origin. We can't rely on tablesync
     445                 :             :                  * worker to remove the origin tracking as if there is any
     446                 :             :                  * error while dropping we won't restart it to drop the
     447                 :             :                  * origin. So passing missing_ok = true.
     448                 :             :                  *
     449                 :             :                  * Lock the subscription and origin in the same order as we
     450                 :             :                  * are doing during DDL commands to avoid deadlocks. See
     451                 :             :                  * AlterSubscription_refresh.
     452                 :             :                  */
     453                 :         206 :                 LockSharedObject(SubscriptionRelationId, MyLogicalRepWorker->subid,
     454                 :             :                                  0, AccessShareLock);
     455                 :             : 
     456         [ +  + ]:         206 :                 if (!rel)
     457                 :         205 :                     rel = table_open(SubscriptionRelRelationId, RowExclusiveLock);
     458                 :             : 
     459                 :         206 :                 ReplicationOriginNameForLogicalRep(MyLogicalRepWorker->subid,
     460                 :             :                                                    rstate->relid,
     461                 :             :                                                    originname,
     462                 :             :                                                    sizeof(originname));
     463                 :         206 :                 replorigin_drop_by_name(originname, true, false);
     464                 :             : 
     465                 :             :                 /*
     466                 :             :                  * Update the state to READY only after the origin cleanup.
     467                 :             :                  */
     468                 :         206 :                 UpdateSubscriptionRelState(MyLogicalRepWorker->subid,
     469                 :         206 :                                            rstate->relid, rstate->state,
     470                 :             :                                            rstate->lsn, true);
     471                 :             :             }
     472                 :             :         }
     473                 :             :         else
     474                 :             :         {
     475                 :             :             LogicalRepWorker *syncworker;
     476                 :             : 
     477                 :             :             /*
     478                 :             :              * Look for a sync worker for this relation.
     479                 :             :              */
     480                 :        1699 :             LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
     481                 :             : 
     482                 :        1699 :             syncworker = logicalrep_worker_find(WORKERTYPE_TABLESYNC,
     483                 :        1699 :                                                 MyLogicalRepWorker->subid,
     484                 :             :                                                 rstate->relid, false);
     485                 :             : 
     486         [ +  + ]:        1699 :             if (syncworker)
     487                 :             :             {
     488                 :             :                 /* Found one, update our copy of its state */
     489                 :         789 :                 SpinLockAcquire(&syncworker->relmutex);
     490                 :         789 :                 rstate->state = syncworker->relstate;
     491                 :         789 :                 rstate->lsn = syncworker->relstate_lsn;
     492         [ +  + ]:         789 :                 if (rstate->state == SUBREL_STATE_SYNCWAIT)
     493                 :             :                 {
     494                 :             :                     /*
     495                 :             :                      * Sync worker is waiting for apply.  Tell sync worker it
     496                 :             :                      * can catchup now.
     497                 :             :                      */
     498                 :         207 :                     syncworker->relstate = SUBREL_STATE_CATCHUP;
     499                 :         207 :                     syncworker->relstate_lsn =
     500                 :         207 :                         Max(syncworker->relstate_lsn, current_lsn);
     501                 :             :                 }
     502                 :         789 :                 SpinLockRelease(&syncworker->relmutex);
     503                 :             : 
     504                 :             :                 /* If we told worker to catch up, wait for it. */
     505         [ +  + ]:         789 :                 if (rstate->state == SUBREL_STATE_SYNCWAIT)
     506                 :             :                 {
     507                 :             :                     /* Signal the sync worker, as it may be waiting for us. */
     508         [ +  - ]:         207 :                     if (syncworker->proc)
     509                 :         207 :                         logicalrep_worker_wakeup_ptr(syncworker);
     510                 :             : 
     511                 :             :                     /* Now safe to release the LWLock */
     512                 :         207 :                     LWLockRelease(LogicalRepWorkerLock);
     513                 :             : 
     514         [ +  - ]:         207 :                     if (started_tx)
     515                 :             :                     {
     516                 :             :                         /*
     517                 :             :                          * We must commit the existing transaction to release
     518                 :             :                          * the existing locks before entering a busy loop.
     519                 :             :                          * This is required to avoid any undetected deadlocks
     520                 :             :                          * due to any existing lock as deadlock detector won't
     521                 :             :                          * be able to detect the waits on the latch.
     522                 :             :                          *
     523                 :             :                          * Also close any tables prior to the commit.
     524                 :             :                          */
     525         [ +  + ]:         207 :                         if (rel)
     526                 :             :                         {
     527                 :          30 :                             table_close(rel, NoLock);
     528                 :          30 :                             rel = NULL;
     529                 :             :                         }
     530                 :         207 :                         CommitTransactionCommand();
     531                 :         207 :                         pgstat_report_stat(false);
     532                 :             :                     }
     533                 :             : 
     534                 :             :                     /*
     535                 :             :                      * Enter busy loop and wait for synchronization worker to
     536                 :             :                      * reach expected state (or die trying).
     537                 :             :                      */
     538                 :         207 :                     StartTransactionCommand();
     539                 :         207 :                     started_tx = true;
     540                 :             : 
     541                 :         207 :                     wait_for_table_state_change(rstate->relid,
     542                 :             :                                                 SUBREL_STATE_SYNCDONE);
     543                 :             :                 }
     544                 :             :                 else
     545                 :         582 :                     LWLockRelease(LogicalRepWorkerLock);
     546                 :             :             }
     547                 :             :             else
     548                 :             :             {
     549                 :             :                 /*
     550                 :             :                  * If there is no sync worker for this table yet, count
     551                 :             :                  * running sync workers for this subscription, while we have
     552                 :             :                  * the lock.
     553                 :             :                  */
     554                 :             :                 int         nsyncworkers =
     555                 :         910 :                     logicalrep_sync_worker_count(MyLogicalRepWorker->subid);
     556                 :             :                 struct tablesync_start_time_mapping *hentry;
     557                 :             :                 bool        found;
     558                 :             : 
     559                 :             :                 /* Now safe to release the LWLock */
     560                 :         910 :                 LWLockRelease(LogicalRepWorkerLock);
     561                 :             : 
     562                 :         910 :                 hentry = hash_search(last_start_times, &rstate->relid,
     563                 :             :                                      HASH_ENTER, &found);
     564         [ +  + ]:         910 :                 if (!found)
     565                 :         214 :                     hentry->last_start_time = 0;
     566                 :             : 
     567                 :         910 :                 launch_sync_worker(WORKERTYPE_TABLESYNC, nsyncworkers,
     568                 :             :                                    rstate->relid, &hentry->last_start_time);
     569                 :             :             }
     570                 :             :         }
     571                 :             :     }
     572                 :             : 
     573                 :             :     /* Close table if opened */
     574         [ +  + ]:        7024 :     if (rel)
     575                 :         175 :         table_close(rel, NoLock);
     576                 :             : 
     577                 :             : 
     578         [ +  + ]:        7024 :     if (started_tx)
     579                 :             :     {
     580                 :             :         /*
     581                 :             :          * Even when the two_phase mode is requested by the user, it remains
     582                 :             :          * as 'pending' until all tablesyncs have reached READY state.
     583                 :             :          *
     584                 :             :          * When this happens, we restart the apply worker and (if the
     585                 :             :          * conditions are still ok) then the two_phase tri-state will become
     586                 :             :          * 'enabled' at that time.
     587                 :             :          *
     588                 :             :          * Note: If the subscription has no tables then leave the state as
     589                 :             :          * PENDING, which allows ALTER SUBSCRIPTION ... REFRESH PUBLICATION to
     590                 :             :          * work.
     591                 :             :          */
     592         [ +  + ]:        1270 :         if (MySubscription->twophasestate == LOGICALREP_TWOPHASE_STATE_PENDING)
     593                 :             :         {
     594                 :          41 :             CommandCounterIncrement();  /* make updates visible */
     595         [ +  + ]:          41 :             if (AllTablesyncsReady())
     596                 :             :             {
     597         [ +  - ]:           7 :                 ereport(LOG,
     598                 :             :                         (errmsg("logical replication apply worker for subscription \"%s\" will restart so that two_phase can be enabled",
     599                 :             :                                 MySubscription->name)));
     600                 :           7 :                 should_exit = true;
     601                 :             :             }
     602                 :             :         }
     603                 :             : 
     604                 :        1270 :         CommitTransactionCommand();
     605                 :        1270 :         pgstat_report_stat(true);
     606                 :             :     }
     607                 :             : 
     608         [ +  + ]:        7024 :     if (should_exit)
     609                 :             :     {
     610                 :             :         /*
     611                 :             :          * Reset the last-start time for this worker so that the launcher will
     612                 :             :          * restart it without waiting for wal_retrieve_retry_interval.
     613                 :             :          */
     614                 :           7 :         ApplyLauncherForgetWorkerStartTime(MySubscription->oid);
     615                 :             : 
     616                 :           7 :         proc_exit(0);
     617                 :             :     }
     618                 :        7017 : }
     619                 :             : 
     620                 :             : /*
     621                 :             :  * Create list of columns for COPY based on logical relation mapping.
     622                 :             :  */
     623                 :             : static List *
     624                 :         221 : make_copy_attnamelist(LogicalRepRelMapEntry *rel)
     625                 :             : {
     626                 :         221 :     List       *attnamelist = NIL;
     627                 :             :     int         i;
     628                 :             : 
     629         [ +  + ]:         584 :     for (i = 0; i < rel->remoterel.natts; i++)
     630                 :             :     {
     631                 :         363 :         attnamelist = lappend(attnamelist,
     632                 :         363 :                               makeString(rel->remoterel.attnames[i]));
     633                 :             :     }
     634                 :             : 
     635                 :             : 
     636                 :         221 :     return attnamelist;
     637                 :             : }
     638                 :             : 
     639                 :             : /*
     640                 :             :  * Data source callback for the COPY FROM, which reads from the remote
     641                 :             :  * connection and passes the data back to our local COPY.
     642                 :             :  *
     643                 :             :  * copybuf serves as transient storage area between calls.  The allocation
     644                 :             :  * actually belongs to walrcv_receive(), which we must not call again until
     645                 :             :  * we have consumed the entire previous buffer!
     646                 :             :  */
     647                 :             : static int
     648                 :       15129 : copy_read_data(void *outbuf, int minread, int maxread)
     649                 :             : {
     650                 :             :     static StringInfoData copybuf = {0};
     651                 :       15129 :     int         bytesread = 0;
     652                 :             :     int         avail;
     653                 :             : 
     654                 :             :     /* If there are some leftover data from previous read, use it. */
     655                 :       15129 :     avail = copybuf.len - copybuf.cursor;
     656         [ -  + ]:       15129 :     if (avail)
     657                 :             :     {
     658         [ #  # ]:           0 :         if (avail > maxread)
     659                 :           0 :             avail = maxread;
     660                 :           0 :         memcpy(outbuf, &copybuf.data[copybuf.cursor], avail);
     661                 :           0 :         copybuf.cursor += avail;
     662                 :           0 :         maxread -= avail;
     663                 :           0 :         bytesread += avail;
     664                 :             :     }
     665                 :             : 
     666   [ +  -  +  - ]:       15130 :     while (maxread > 0 && bytesread < minread)
     667                 :             :     {
     668                 :       15130 :         pgsocket    fd = PGINVALID_SOCKET;
     669                 :             :         int         len;
     670                 :       15130 :         char       *buf = NULL;
     671                 :             : 
     672                 :             :         for (;;)
     673                 :             :         {
     674                 :             :             /* Try and read more data. We must have consumed all we had. */
     675                 :           0 :             Assert(copybuf.cursor == copybuf.len);
     676                 :       15130 :             len = walrcv_receive(LogRepWorkerWalRcvConn, &buf, &fd);
     677                 :             : 
     678         [ -  + ]:       15130 :             CHECK_FOR_INTERRUPTS();
     679                 :             : 
     680         [ +  + ]:       15130 :             if (len == 0)
     681                 :           1 :                 break;
     682         [ +  + ]:       15129 :             else if (len < 0)
     683                 :       15129 :                 return bytesread;
     684                 :             :             else
     685                 :             :             {
     686                 :             :                 /* Process the data */
     687                 :       14910 :                 initReadOnlyStringInfo(&copybuf, buf, len);
     688                 :             : 
     689                 :       14910 :                 avail = copybuf.len - copybuf.cursor;
     690         [ -  + ]:       14910 :                 if (avail > maxread)
     691                 :           0 :                     avail = maxread;
     692                 :       14910 :                 memcpy(outbuf, &copybuf.data[copybuf.cursor], avail);
     693                 :       14910 :                 outbuf = (char *) outbuf + avail;
     694                 :       14910 :                 copybuf.cursor += avail;
     695                 :       14910 :                 maxread -= avail;
     696                 :       14910 :                 bytesread += avail;
     697                 :             :             }
     698                 :             : 
     699   [ +  -  +  - ]:       14910 :             if (maxread <= 0 || bytesread >= minread)
     700                 :       14910 :                 return bytesread;
     701                 :             :         }
     702                 :             : 
     703                 :             :         /*
     704                 :             :          * Wait for more data or latch.
     705                 :             :          */
     706                 :           1 :         (void) WaitLatchOrSocket(MyLatch,
     707                 :             :                                  WL_SOCKET_READABLE | WL_LATCH_SET |
     708                 :             :                                  WL_TIMEOUT | WL_EXIT_ON_PM_DEATH,
     709                 :             :                                  fd, 1000L, WAIT_EVENT_LOGICAL_SYNC_DATA);
     710                 :             : 
     711                 :           1 :         ResetLatch(MyLatch);
     712                 :             :     }
     713                 :             : 
     714                 :           0 :     return bytesread;
     715                 :             : }
     716                 :             : 
     717                 :             : 
     718                 :             : /*
     719                 :             :  * Get information about remote relation in similar fashion the RELATION
     720                 :             :  * message provides during replication.
     721                 :             :  *
     722                 :             :  * This function also returns (a) the relation qualifications to be used in
     723                 :             :  * the COPY command, and (b) whether the remote relation has published any
     724                 :             :  * generated column.
     725                 :             :  */
     726                 :             : static void
     727                 :         224 : fetch_remote_table_info(char *nspname, char *relname, LogicalRepRelation *lrel,
     728                 :             :                         List **qual, bool *gencol_published)
     729                 :             : {
     730                 :             :     WalRcvExecResult *res;
     731                 :             :     StringInfoData cmd;
     732                 :             :     TupleTableSlot *slot;
     733                 :         224 :     Oid         tableRow[] = {OIDOID, CHAROID, CHAROID};
     734                 :         224 :     Oid         attrRow[] = {INT2OID, TEXTOID, OIDOID, BOOLOID, BOOLOID};
     735                 :         224 :     Oid         qualRow[] = {TEXTOID};
     736                 :             :     bool        isnull;
     737                 :             :     int         natt;
     738                 :         224 :     StringInfo  pub_names = NULL;
     739                 :         224 :     Bitmapset  *included_cols = NULL;
     740                 :         224 :     int         server_version = walrcv_server_version(LogRepWorkerWalRcvConn);
     741                 :             : 
     742                 :         224 :     lrel->nspname = nspname;
     743                 :         224 :     lrel->relname = relname;
     744                 :             : 
     745                 :             :     /* First fetch Oid and replica identity. */
     746                 :         224 :     initStringInfo(&cmd);
     747                 :         224 :     appendStringInfo(&cmd, "SELECT c.oid, c.relreplident, c.relkind"
     748                 :             :                      "  FROM pg_catalog.pg_class c"
     749                 :             :                      "  INNER JOIN pg_catalog.pg_namespace n"
     750                 :             :                      "        ON (c.relnamespace = n.oid)"
     751                 :             :                      " WHERE n.nspname = %s"
     752                 :             :                      "   AND c.relname = %s",
     753                 :             :                      quote_literal_cstr(nspname),
     754                 :             :                      quote_literal_cstr(relname));
     755                 :         224 :     res = walrcv_exec(LogRepWorkerWalRcvConn, cmd.data,
     756                 :             :                       lengthof(tableRow), tableRow);
     757                 :             : 
     758         [ -  + ]:         224 :     if (res->status != WALRCV_OK_TUPLES)
     759         [ #  # ]:           0 :         ereport(ERROR,
     760                 :             :                 (errcode(ERRCODE_CONNECTION_FAILURE),
     761                 :             :                  errmsg("could not fetch table info for table \"%s.%s\" from publisher: %s",
     762                 :             :                         nspname, relname, res->err)));
     763                 :             : 
     764                 :         224 :     slot = MakeSingleTupleTableSlot(res->tupledesc, &TTSOpsMinimalTuple);
     765         [ -  + ]:         224 :     if (!tuplestore_gettupleslot(res->tuplestore, true, false, slot))
     766         [ #  # ]:           0 :         ereport(ERROR,
     767                 :             :                 (errcode(ERRCODE_UNDEFINED_OBJECT),
     768                 :             :                  errmsg("table \"%s.%s\" not found on publisher",
     769                 :             :                         nspname, relname)));
     770                 :             : 
     771                 :         224 :     lrel->remoteid = DatumGetObjectId(slot_getattr(slot, 1, &isnull));
     772                 :             :     Assert(!isnull);
     773                 :         224 :     lrel->replident = DatumGetChar(slot_getattr(slot, 2, &isnull));
     774                 :             :     Assert(!isnull);
     775                 :         224 :     lrel->relkind = DatumGetChar(slot_getattr(slot, 3, &isnull));
     776                 :             :     Assert(!isnull);
     777                 :             : 
     778                 :         224 :     ExecDropSingleTupleTableSlot(slot);
     779                 :         224 :     walrcv_clear_result(res);
     780                 :             : 
     781                 :             : 
     782                 :             :     /*
     783                 :             :      * Get column lists for each relation.
     784                 :             :      *
     785                 :             :      * We need to do this before fetching info about column names and types,
     786                 :             :      * so that we can skip columns that should not be replicated.
     787                 :             :      */
     788         [ +  - ]:         224 :     if (server_version >= 150000)
     789                 :             :     {
     790                 :             :         WalRcvExecResult *pubres;
     791                 :             :         TupleTableSlot *tslot;
     792                 :         224 :         Oid         attrsRow[] = {INT2VECTOROID};
     793                 :             : 
     794                 :             :         /* Build the pub_names comma-separated string. */
     795                 :         224 :         pub_names = makeStringInfo();
     796                 :         224 :         GetPublicationsStr(MySubscription->publications, pub_names, true);
     797                 :             : 
     798                 :             :         /*
     799                 :             :          * Fetch info about column lists for the relation (from all the
     800                 :             :          * publications).
     801                 :             :          */
     802                 :         224 :         resetStringInfo(&cmd);
     803                 :             : 
     804         [ +  - ]:         224 :         if (server_version >= 190000)
     805                 :             :         {
     806                 :             :             /*
     807                 :             :              * We can pass both publication names and relid to
     808                 :             :              * pg_get_publication_tables() since version 19.
     809                 :             :              */
     810                 :         224 :             appendStringInfo(&cmd,
     811                 :             :                              "SELECT DISTINCT"
     812                 :             :                              "  (CASE WHEN (array_length(gpt.attrs, 1) = c.relnatts)"
     813                 :             :                              "   THEN NULL ELSE gpt.attrs END)"
     814                 :             :                              "  FROM pg_get_publication_tables(ARRAY[%s], %u) gpt,"
     815                 :             :                              "  pg_class c"
     816                 :             :                              " WHERE c.oid = gpt.relid",
     817                 :             :                              pub_names->data,
     818                 :             :                              lrel->remoteid);
     819                 :             :         }
     820                 :             :         else
     821                 :           0 :             appendStringInfo(&cmd,
     822                 :             :                              "SELECT DISTINCT"
     823                 :             :                              "  (CASE WHEN (array_length(gpt.attrs, 1) = c.relnatts)"
     824                 :             :                              "   THEN NULL ELSE gpt.attrs END)"
     825                 :             :                              "  FROM pg_publication p,"
     826                 :             :                              "  LATERAL pg_get_publication_tables(p.pubname) gpt,"
     827                 :             :                              "  pg_class c"
     828                 :             :                              " WHERE gpt.relid = %u AND c.oid = gpt.relid"
     829                 :             :                              "   AND p.pubname IN ( %s )",
     830                 :             :                              lrel->remoteid,
     831                 :             :                              pub_names->data);
     832                 :             : 
     833                 :         224 :         pubres = walrcv_exec(LogRepWorkerWalRcvConn, cmd.data,
     834                 :             :                              lengthof(attrsRow), attrsRow);
     835                 :             : 
     836         [ -  + ]:         224 :         if (pubres->status != WALRCV_OK_TUPLES)
     837         [ #  # ]:           0 :             ereport(ERROR,
     838                 :             :                     (errcode(ERRCODE_CONNECTION_FAILURE),
     839                 :             :                      errmsg("could not fetch column list info for table \"%s.%s\" from publisher: %s",
     840                 :             :                             nspname, relname, pubres->err)));
     841                 :             : 
     842                 :             :         /*
     843                 :             :          * We don't support the case where the column list is different for
     844                 :             :          * the same table when combining publications. See comments atop
     845                 :             :          * fetch_relation_list. So there should be only one row returned.
     846                 :             :          * Although we already checked this when creating the subscription, we
     847                 :             :          * still need to check here in case the column list was changed after
     848                 :             :          * creating the subscription and before the sync worker is started.
     849                 :             :          */
     850         [ -  + ]:         224 :         if (tuplestore_tuple_count(pubres->tuplestore) > 1)
     851         [ #  # ]:           0 :             ereport(ERROR,
     852                 :             :                     errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     853                 :             :                     errmsg("cannot use different column lists for table \"%s.%s\" in different publications",
     854                 :             :                            nspname, relname));
     855                 :             : 
     856                 :             :         /*
     857                 :             :          * Get the column list and build a single bitmap with the attnums.
     858                 :             :          *
     859                 :             :          * If we find a NULL value, it means all the columns should be
     860                 :             :          * replicated.
     861                 :             :          */
     862                 :         224 :         tslot = MakeSingleTupleTableSlot(pubres->tupledesc, &TTSOpsMinimalTuple);
     863         [ +  + ]:         224 :         if (tuplestore_gettupleslot(pubres->tuplestore, true, false, tslot))
     864                 :             :         {
     865                 :         223 :             Datum       cfval = slot_getattr(tslot, 1, &isnull);
     866                 :             : 
     867         [ +  + ]:         223 :             if (!isnull)
     868                 :             :             {
     869                 :             :                 ArrayType  *arr;
     870                 :             :                 int         nelems;
     871                 :             :                 int16      *elems;
     872                 :             : 
     873                 :          22 :                 arr = DatumGetArrayTypeP(cfval);
     874                 :          22 :                 nelems = ARR_DIMS(arr)[0];
     875         [ -  + ]:          22 :                 elems = (int16 *) ARR_DATA_PTR(arr);
     876                 :             : 
     877         [ +  + ]:          59 :                 for (natt = 0; natt < nelems; natt++)
     878                 :          37 :                     included_cols = bms_add_member(included_cols, elems[natt]);
     879                 :             :             }
     880                 :             : 
     881                 :         223 :             ExecClearTuple(tslot);
     882                 :             :         }
     883                 :         224 :         ExecDropSingleTupleTableSlot(tslot);
     884                 :             : 
     885                 :         224 :         walrcv_clear_result(pubres);
     886                 :             :     }
     887                 :             : 
     888                 :             :     /*
     889                 :             :      * Now fetch column names and types.
     890                 :             :      */
     891                 :         224 :     resetStringInfo(&cmd);
     892                 :         224 :     appendStringInfoString(&cmd,
     893                 :             :                            "SELECT a.attnum,"
     894                 :             :                            "       a.attname,"
     895                 :             :                            "       a.atttypid,"
     896                 :             :                            "       a.attnum = ANY(i.indkey)");
     897                 :             : 
     898                 :             :     /* Generated columns can be replicated since version 18. */
     899         [ +  - ]:         224 :     if (server_version >= 180000)
     900                 :         224 :         appendStringInfoString(&cmd, ", a.attgenerated != ''");
     901                 :             : 
     902         [ +  - ]:         448 :     appendStringInfo(&cmd,
     903                 :             :                      "  FROM pg_catalog.pg_attribute a"
     904                 :             :                      "  LEFT JOIN pg_catalog.pg_index i"
     905                 :             :                      "       ON (i.indexrelid = pg_get_replica_identity_index(%u))"
     906                 :             :                      " WHERE a.attnum > 0::pg_catalog.int2"
     907                 :             :                      "   AND NOT a.attisdropped %s"
     908                 :             :                      "   AND a.attrelid = %u"
     909                 :             :                      " ORDER BY a.attnum",
     910                 :             :                      lrel->remoteid,
     911         [ -  + ]:         224 :                      (server_version >= 120000 && server_version < 180000 ?
     912                 :             :                       "AND a.attgenerated = ''" : ""),
     913                 :             :                      lrel->remoteid);
     914         [ +  - ]:         224 :     res = walrcv_exec(LogRepWorkerWalRcvConn, cmd.data,
     915                 :             :                       server_version >= 180000 ? lengthof(attrRow) : lengthof(attrRow) - 1, attrRow);
     916                 :             : 
     917         [ +  + ]:         224 :     if (res->status != WALRCV_OK_TUPLES)
     918         [ +  - ]:           1 :         ereport(ERROR,
     919                 :             :                 (errcode(ERRCODE_CONNECTION_FAILURE),
     920                 :             :                  errmsg("could not fetch table info for table \"%s.%s\" from publisher: %s",
     921                 :             :                         nspname, relname, res->err)));
     922                 :             : 
     923                 :             :     /* We don't know the number of rows coming, so allocate enough space. */
     924                 :         223 :     lrel->attnames = palloc0_array(char *, MaxTupleAttributeNumber);
     925                 :         223 :     lrel->atttyps = palloc0_array(Oid, MaxTupleAttributeNumber);
     926                 :         223 :     lrel->attkeys = NULL;
     927                 :             : 
     928                 :             :     /*
     929                 :             :      * Store the columns as a list of names.  Ignore those that are not
     930                 :             :      * present in the column list, if there is one.
     931                 :             :      */
     932                 :         223 :     natt = 0;
     933                 :         223 :     slot = MakeSingleTupleTableSlot(res->tupledesc, &TTSOpsMinimalTuple);
     934         [ +  + ]:         623 :     while (tuplestore_gettupleslot(res->tuplestore, true, false, slot))
     935                 :             :     {
     936                 :             :         char       *rel_colname;
     937                 :             :         AttrNumber  attnum;
     938                 :             : 
     939                 :         400 :         attnum = DatumGetInt16(slot_getattr(slot, 1, &isnull));
     940                 :             :         Assert(!isnull);
     941                 :             : 
     942                 :             :         /* If the column is not in the column list, skip it. */
     943   [ +  +  +  + ]:         400 :         if (included_cols != NULL && !bms_is_member(attnum, included_cols))
     944                 :             :         {
     945                 :          31 :             ExecClearTuple(slot);
     946                 :          31 :             continue;
     947                 :             :         }
     948                 :             : 
     949                 :         369 :         rel_colname = TextDatumGetCString(slot_getattr(slot, 2, &isnull));
     950                 :             :         Assert(!isnull);
     951                 :             : 
     952                 :         369 :         lrel->attnames[natt] = rel_colname;
     953                 :         369 :         lrel->atttyps[natt] = DatumGetObjectId(slot_getattr(slot, 3, &isnull));
     954                 :             :         Assert(!isnull);
     955                 :             : 
     956         [ +  + ]:         369 :         if (DatumGetBool(slot_getattr(slot, 4, &isnull)))
     957                 :         118 :             lrel->attkeys = bms_add_member(lrel->attkeys, natt);
     958                 :             : 
     959                 :             :         /* Remember if the remote table has published any generated column. */
     960   [ +  -  +  - ]:         369 :         if (server_version >= 180000 && !(*gencol_published))
     961                 :             :         {
     962                 :         369 :             *gencol_published = DatumGetBool(slot_getattr(slot, 5, &isnull));
     963                 :             :             Assert(!isnull);
     964                 :             :         }
     965                 :             : 
     966                 :             :         /* Should never happen. */
     967         [ -  + ]:         369 :         if (++natt >= MaxTupleAttributeNumber)
     968         [ #  # ]:           0 :             elog(ERROR, "too many columns in remote table \"%s.%s\"",
     969                 :             :                  nspname, relname);
     970                 :             : 
     971                 :         369 :         ExecClearTuple(slot);
     972                 :             :     }
     973                 :         223 :     ExecDropSingleTupleTableSlot(slot);
     974                 :             : 
     975                 :         223 :     lrel->natts = natt;
     976                 :             : 
     977                 :         223 :     walrcv_clear_result(res);
     978                 :             : 
     979                 :             :     /*
     980                 :             :      * Get relation's row filter expressions. DISTINCT avoids the same
     981                 :             :      * expression of a table in multiple publications from being included
     982                 :             :      * multiple times in the final expression.
     983                 :             :      *
     984                 :             :      * We need to copy the row even if it matches just one of the
     985                 :             :      * publications, so we later combine all the quals with OR.
     986                 :             :      *
     987                 :             :      * For initial synchronization, row filtering can be ignored in following
     988                 :             :      * cases:
     989                 :             :      *
     990                 :             :      * 1) one of the subscribed publications for the table hasn't specified
     991                 :             :      * any row filter
     992                 :             :      *
     993                 :             :      * 2) one of the subscribed publications has puballtables set to true
     994                 :             :      *
     995                 :             :      * 3) one of the subscribed publications is declared as TABLES IN SCHEMA
     996                 :             :      * that includes this relation
     997                 :             :      */
     998         [ +  - ]:         223 :     if (server_version >= 150000)
     999                 :             :     {
    1000                 :             :         /* Reuse the already-built pub_names. */
    1001                 :             :         Assert(pub_names != NULL);
    1002                 :             : 
    1003                 :             :         /* Check for row filters. */
    1004                 :         223 :         resetStringInfo(&cmd);
    1005                 :             : 
    1006         [ +  - ]:         223 :         if (server_version >= 190000)
    1007                 :             :         {
    1008                 :             :             /*
    1009                 :             :              * We can pass both publication names and relid to
    1010                 :             :              * pg_get_publication_tables() since version 19.
    1011                 :             :              */
    1012                 :         223 :             appendStringInfo(&cmd,
    1013                 :             :                              "SELECT DISTINCT pg_get_expr(gpt.qual, gpt.relid)"
    1014                 :             :                              "  FROM pg_get_publication_tables(ARRAY[%s], %u) gpt",
    1015                 :             :                              pub_names->data,
    1016                 :             :                              lrel->remoteid);
    1017                 :             :         }
    1018                 :             :         else
    1019                 :           0 :             appendStringInfo(&cmd,
    1020                 :             :                              "SELECT DISTINCT pg_get_expr(gpt.qual, gpt.relid)"
    1021                 :             :                              "  FROM pg_publication p,"
    1022                 :             :                              "  LATERAL pg_get_publication_tables(p.pubname) gpt"
    1023                 :             :                              " WHERE gpt.relid = %u"
    1024                 :             :                              "   AND p.pubname IN ( %s )",
    1025                 :             :                              lrel->remoteid,
    1026                 :             :                              pub_names->data);
    1027                 :             : 
    1028                 :         223 :         res = walrcv_exec(LogRepWorkerWalRcvConn, cmd.data, 1, qualRow);
    1029                 :             : 
    1030         [ -  + ]:         223 :         if (res->status != WALRCV_OK_TUPLES)
    1031         [ #  # ]:           0 :             ereport(ERROR,
    1032                 :             :                     (errmsg("could not fetch table WHERE clause info for table \"%s.%s\" from publisher: %s",
    1033                 :             :                             nspname, relname, res->err)));
    1034                 :             : 
    1035                 :             :         /*
    1036                 :             :          * Multiple row filter expressions for the same table will be combined
    1037                 :             :          * by COPY using OR. If any of the filter expressions for this table
    1038                 :             :          * are null, it means the whole table will be copied. In this case it
    1039                 :             :          * is not necessary to construct a unified row filter expression at
    1040                 :             :          * all.
    1041                 :             :          */
    1042                 :         223 :         slot = MakeSingleTupleTableSlot(res->tupledesc, &TTSOpsMinimalTuple);
    1043         [ +  + ]:         236 :         while (tuplestore_gettupleslot(res->tuplestore, true, false, slot))
    1044                 :             :         {
    1045                 :         225 :             Datum       rf = slot_getattr(slot, 1, &isnull);
    1046                 :             : 
    1047         [ +  + ]:         225 :             if (!isnull)
    1048                 :          13 :                 *qual = lappend(*qual, makeString(TextDatumGetCString(rf)));
    1049                 :             :             else
    1050                 :             :             {
    1051                 :             :                 /* Ignore filters and cleanup as necessary. */
    1052         [ +  + ]:         212 :                 if (*qual)
    1053                 :             :                 {
    1054                 :           1 :                     list_free_deep(*qual);
    1055                 :           1 :                     *qual = NIL;
    1056                 :             :                 }
    1057                 :         212 :                 break;
    1058                 :             :             }
    1059                 :             : 
    1060                 :          13 :             ExecClearTuple(slot);
    1061                 :             :         }
    1062                 :         223 :         ExecDropSingleTupleTableSlot(slot);
    1063                 :             : 
    1064                 :         223 :         walrcv_clear_result(res);
    1065                 :         223 :         destroyStringInfo(pub_names);
    1066                 :             :     }
    1067                 :             : 
    1068                 :         223 :     pfree(cmd.data);
    1069                 :         223 : }
    1070                 :             : 
    1071                 :             : /*
    1072                 :             :  * Copy existing data of a table from publisher.
    1073                 :             :  *
    1074                 :             :  * Caller is responsible for locking the local relation.
    1075                 :             :  */
    1076                 :             : static void
    1077                 :         224 : copy_table(Relation rel)
    1078                 :             : {
    1079                 :             :     LogicalRepRelMapEntry *relmapentry;
    1080                 :             :     LogicalRepRelation lrel;
    1081                 :         224 :     List       *qual = NIL;
    1082                 :             :     WalRcvExecResult *res;
    1083                 :             :     StringInfoData cmd;
    1084                 :             :     CopyFromState cstate;
    1085                 :             :     List       *attnamelist;
    1086                 :             :     ParseState *pstate;
    1087                 :         224 :     List       *options = NIL;
    1088                 :         224 :     bool        gencol_published = false;
    1089                 :         224 :     int         server_version = walrcv_server_version(LogRepWorkerWalRcvConn);
    1090                 :             : 
    1091                 :             :     /* Get the publisher relation info. */
    1092                 :         224 :     fetch_remote_table_info(get_namespace_name(RelationGetNamespace(rel)),
    1093                 :         224 :                             RelationGetRelationName(rel), &lrel, &qual,
    1094                 :             :                             &gencol_published);
    1095                 :             : 
    1096                 :             :     /* Put the relation into relmap. */
    1097                 :         223 :     logicalrep_relmap_update(&lrel);
    1098                 :             : 
    1099                 :             :     /* Map the publisher relation to local one. */
    1100                 :         223 :     relmapentry = logicalrep_rel_open(lrel.remoteid, NoLock);
    1101                 :             :     Assert(rel == relmapentry->localrel);
    1102                 :             : 
    1103                 :             :     /* Start copy on the publisher. */
    1104                 :         221 :     initStringInfo(&cmd);
    1105                 :             : 
    1106                 :             :     /*
    1107                 :             :      * Regular or partitioned table with no row filter or generated columns.
    1108                 :             :      *
    1109                 :             :      * "COPY table TO" on a partitioned table is supported since v19.
    1110                 :             :      */
    1111         [ +  + ]:         221 :     if ((lrel.relkind == RELKIND_RELATION ||
    1112   [ +  -  +  - ]:          17 :          (lrel.relkind == RELKIND_PARTITIONED_TABLE && server_version >= 190000)) &&
    1113   [ +  +  +  + ]:         221 :         qual == NIL && !gencol_published)
    1114                 :             :     {
    1115                 :         207 :         appendStringInfo(&cmd, "COPY %s",
    1116                 :         207 :                          quote_qualified_identifier(lrel.nspname, lrel.relname));
    1117                 :             : 
    1118                 :             :         /* If the table has columns, then specify the columns */
    1119         [ +  + ]:         207 :         if (lrel.natts)
    1120                 :             :         {
    1121                 :         206 :             appendStringInfoString(&cmd, " (");
    1122                 :             : 
    1123                 :             :             /*
    1124                 :             :              * XXX Do we need to list the columns in all cases? Maybe we're
    1125                 :             :              * replicating all columns?
    1126                 :             :              */
    1127         [ +  + ]:         548 :             for (int i = 0; i < lrel.natts; i++)
    1128                 :             :             {
    1129         [ +  + ]:         342 :                 if (i > 0)
    1130                 :         136 :                     appendStringInfoString(&cmd, ", ");
    1131                 :             : 
    1132                 :         342 :                 appendStringInfoString(&cmd, quote_identifier(lrel.attnames[i]));
    1133                 :             :             }
    1134                 :             : 
    1135                 :         206 :             appendStringInfoChar(&cmd, ')');
    1136                 :             :         }
    1137                 :             : 
    1138                 :         207 :         appendStringInfoString(&cmd, " TO STDOUT");
    1139                 :             :     }
    1140                 :             :     else
    1141                 :             :     {
    1142                 :             :         /*
    1143                 :             :          * For non-tables and tables with row filters, we need to do COPY
    1144                 :             :          * (SELECT ...), but we can't just do SELECT * because we may need to
    1145                 :             :          * copy only subset of columns including generated columns. For tables
    1146                 :             :          * with any row filters, build a SELECT query with OR'ed row filters
    1147                 :             :          * for COPY.
    1148                 :             :          *
    1149                 :             :          * We also need to use this same COPY (SELECT ...) syntax when
    1150                 :             :          * generated columns are published, because copy of generated columns
    1151                 :             :          * is not supported by the normal COPY.
    1152                 :             :          */
    1153                 :          14 :         appendStringInfoString(&cmd, "COPY (SELECT ");
    1154         [ +  + ]:          35 :         for (int i = 0; i < lrel.natts; i++)
    1155                 :             :         {
    1156                 :          21 :             appendStringInfoString(&cmd, quote_identifier(lrel.attnames[i]));
    1157         [ +  + ]:          21 :             if (i < lrel.natts - 1)
    1158                 :           7 :                 appendStringInfoString(&cmd, ", ");
    1159                 :             :         }
    1160                 :             : 
    1161                 :          14 :         appendStringInfoString(&cmd, " FROM ");
    1162                 :             : 
    1163                 :             :         /*
    1164                 :             :          * For regular tables, make sure we don't copy data from a child that
    1165                 :             :          * inherits the named table as those will be copied separately.
    1166                 :             :          */
    1167         [ +  + ]:          14 :         if (lrel.relkind == RELKIND_RELATION)
    1168                 :          11 :             appendStringInfoString(&cmd, "ONLY ");
    1169                 :             : 
    1170                 :          14 :         appendStringInfoString(&cmd, quote_qualified_identifier(lrel.nspname, lrel.relname));
    1171                 :             :         /* list of OR'ed filters */
    1172         [ +  + ]:          14 :         if (qual != NIL)
    1173                 :             :         {
    1174                 :             :             ListCell   *lc;
    1175                 :          11 :             char       *q = strVal(linitial(qual));
    1176                 :             : 
    1177                 :          11 :             appendStringInfo(&cmd, " WHERE %s", q);
    1178   [ +  -  +  +  :          12 :             for_each_from(lc, qual, 1)
                   +  + ]
    1179                 :             :             {
    1180                 :           1 :                 q = strVal(lfirst(lc));
    1181                 :           1 :                 appendStringInfo(&cmd, " OR %s", q);
    1182                 :             :             }
    1183                 :          11 :             list_free_deep(qual);
    1184                 :             :         }
    1185                 :             : 
    1186                 :          14 :         appendStringInfoString(&cmd, ") TO STDOUT");
    1187                 :             :     }
    1188                 :             : 
    1189                 :             :     /*
    1190                 :             :      * Prior to v16, initial table synchronization will use text format even
    1191                 :             :      * if the binary option is enabled for a subscription.
    1192                 :             :      */
    1193   [ +  -  +  + ]:         221 :     if (server_version >= 160000 && MySubscription->binary)
    1194                 :             :     {
    1195                 :           5 :         appendStringInfoString(&cmd, " WITH (FORMAT binary)");
    1196                 :           5 :         options = list_make1(makeDefElem("format",
    1197                 :             :                                          (Node *) makeString("binary"), -1));
    1198                 :             :     }
    1199                 :             : 
    1200                 :         221 :     res = walrcv_exec(LogRepWorkerWalRcvConn, cmd.data, 0, NULL);
    1201                 :         221 :     pfree(cmd.data);
    1202         [ -  + ]:         221 :     if (res->status != WALRCV_OK_COPY_OUT)
    1203         [ #  # ]:           0 :         ereport(ERROR,
    1204                 :             :                 (errcode(ERRCODE_CONNECTION_FAILURE),
    1205                 :             :                  errmsg("could not start initial contents copy for table \"%s.%s\": %s",
    1206                 :             :                         lrel.nspname, lrel.relname, res->err)));
    1207                 :         221 :     walrcv_clear_result(res);
    1208                 :             : 
    1209                 :         221 :     pstate = make_parsestate(NULL);
    1210                 :         221 :     (void) addRangeTableEntryForRelation(pstate, rel, AccessShareLock,
    1211                 :             :                                          NULL, false, false);
    1212                 :             : 
    1213                 :         221 :     attnamelist = make_copy_attnamelist(relmapentry);
    1214                 :         221 :     cstate = BeginCopyFrom(pstate, rel, NULL, NULL, false, copy_read_data, attnamelist, options);
    1215                 :             : 
    1216                 :             :     /* Do the copy */
    1217                 :         220 :     (void) CopyFrom(cstate);
    1218                 :         209 :     EndCopyFrom(cstate);
    1219                 :             : 
    1220                 :         209 :     logicalrep_rel_close(relmapentry, NoLock);
    1221                 :         209 : }
    1222                 :             : 
    1223                 :             : /*
    1224                 :             :  * Determine the tablesync slot name.
    1225                 :             :  *
    1226                 :             :  * The name must not exceed NAMEDATALEN - 1 because of remote node constraints
    1227                 :             :  * on slot name length. We append system_identifier to avoid slot_name
    1228                 :             :  * collision with subscriptions in other clusters. With the current scheme
    1229                 :             :  * pg_%u_sync_%u_UINT64_FORMAT (3 + 10 + 6 + 10 + 20 + '\0'), the maximum
    1230                 :             :  * length of slot_name will be 50.
    1231                 :             :  *
    1232                 :             :  * The returned slot name is stored in the supplied buffer (syncslotname) with
    1233                 :             :  * the given size.
    1234                 :             :  *
    1235                 :             :  * Note: We don't use the subscription slot name as part of tablesync slot name
    1236                 :             :  * because we are responsible for cleaning up these slots and it could become
    1237                 :             :  * impossible to recalculate what name to cleanup if the subscription slot name
    1238                 :             :  * had changed.
    1239                 :             :  */
    1240                 :             : void
    1241                 :         438 : ReplicationSlotNameForTablesync(Oid suboid, Oid relid,
    1242                 :             :                                 char *syncslotname, Size szslot)
    1243                 :             : {
    1244                 :         438 :     snprintf(syncslotname, szslot, "pg_%u_sync_%u_" UINT64_FORMAT, suboid,
    1245                 :             :              relid, GetSystemIdentifier());
    1246                 :         438 : }
    1247                 :             : 
    1248                 :             : /*
    1249                 :             :  * Start syncing the table in the sync worker.
    1250                 :             :  *
    1251                 :             :  * If nothing needs to be done to sync the table, we exit the worker without
    1252                 :             :  * any further action.
    1253                 :             :  *
    1254                 :             :  * The returned slot name is palloc'ed in current memory context.
    1255                 :             :  */
    1256                 :             : static char *
    1257                 :         224 : LogicalRepSyncTableStart(XLogRecPtr *origin_startpos)
    1258                 :             : {
    1259                 :             :     char       *slotname;
    1260                 :             :     char       *err;
    1261                 :             :     char        relstate;
    1262                 :             :     XLogRecPtr  relstate_lsn;
    1263                 :             :     Relation    rel;
    1264                 :             :     AclResult   aclresult;
    1265                 :             :     WalRcvExecResult *res;
    1266                 :             :     char        originname[NAMEDATALEN];
    1267                 :             :     ReplOriginId originid;
    1268                 :             :     UserContext ucxt;
    1269                 :             :     bool        must_use_password;
    1270                 :             :     bool        run_as_owner;
    1271                 :             : 
    1272                 :             :     /* Check the state of the table synchronization. */
    1273                 :         224 :     StartTransactionCommand();
    1274                 :         224 :     relstate = GetSubscriptionRelState(MyLogicalRepWorker->subid,
    1275                 :         224 :                                        MyLogicalRepWorker->relid,
    1276                 :             :                                        &relstate_lsn);
    1277                 :         224 :     CommitTransactionCommand();
    1278                 :             : 
    1279                 :             :     /* Is the use of a password mandatory? */
    1280         [ +  + ]:         443 :     must_use_password = MySubscription->passwordrequired &&
    1281         [ -  + ]:         219 :         !MySubscription->ownersuperuser;
    1282                 :             : 
    1283                 :         224 :     SpinLockAcquire(&MyLogicalRepWorker->relmutex);
    1284                 :         224 :     MyLogicalRepWorker->relstate = relstate;
    1285                 :         224 :     MyLogicalRepWorker->relstate_lsn = relstate_lsn;
    1286                 :         224 :     SpinLockRelease(&MyLogicalRepWorker->relmutex);
    1287                 :             : 
    1288                 :             :     /*
    1289                 :             :      * If synchronization is already done or no longer necessary, exit now
    1290                 :             :      * that we've updated shared memory state.
    1291                 :             :      */
    1292         [ -  + ]:         224 :     switch (relstate)
    1293                 :             :     {
    1294                 :           0 :         case SUBREL_STATE_SYNCDONE:
    1295                 :             :         case SUBREL_STATE_READY:
    1296                 :             :         case SUBREL_STATE_UNKNOWN:
    1297                 :           0 :             FinishSyncWorker(); /* doesn't return */
    1298                 :             :     }
    1299                 :             : 
    1300                 :             :     /* Calculate the name of the tablesync slot. */
    1301                 :         224 :     slotname = (char *) palloc(NAMEDATALEN);
    1302                 :         224 :     ReplicationSlotNameForTablesync(MySubscription->oid,
    1303                 :         224 :                                     MyLogicalRepWorker->relid,
    1304                 :             :                                     slotname,
    1305                 :             :                                     NAMEDATALEN);
    1306                 :             : 
    1307                 :             :     /*
    1308                 :             :      * Here we use the slot name instead of the subscription name as the
    1309                 :             :      * application_name, so that it is different from the leader apply worker,
    1310                 :             :      * so that synchronous replication can distinguish them.
    1311                 :             :      */
    1312                 :         224 :     LogRepWorkerWalRcvConn =
    1313                 :         224 :         walrcv_connect(MySubscriptionConninfo, true, true,
    1314                 :             :                        must_use_password,
    1315                 :             :                        slotname, &err);
    1316         [ -  + ]:         224 :     if (LogRepWorkerWalRcvConn == NULL)
    1317         [ #  # ]:           0 :         ereport(ERROR,
    1318                 :             :                 (errcode(ERRCODE_CONNECTION_FAILURE),
    1319                 :             :                  errmsg("table synchronization worker for subscription \"%s\" could not connect to the publisher: %s",
    1320                 :             :                         MySubscription->name, err)));
    1321                 :             : 
    1322                 :             :     Assert(MyLogicalRepWorker->relstate == SUBREL_STATE_INIT ||
    1323                 :             :            MyLogicalRepWorker->relstate == SUBREL_STATE_DATASYNC ||
    1324                 :             :            MyLogicalRepWorker->relstate == SUBREL_STATE_FINISHEDCOPY);
    1325                 :             : 
    1326                 :             :     /* Assign the origin tracking record name. */
    1327                 :         224 :     ReplicationOriginNameForLogicalRep(MySubscription->oid,
    1328                 :         224 :                                        MyLogicalRepWorker->relid,
    1329                 :             :                                        originname,
    1330                 :             :                                        sizeof(originname));
    1331                 :             : 
    1332         [ +  + ]:         224 :     if (MyLogicalRepWorker->relstate == SUBREL_STATE_DATASYNC)
    1333                 :             :     {
    1334                 :             :         /*
    1335                 :             :          * We have previously errored out before finishing the copy so the
    1336                 :             :          * replication slot might exist. We want to remove the slot if it
    1337                 :             :          * already exists and proceed.
    1338                 :             :          *
    1339                 :             :          * XXX We could also instead try to drop the slot, last time we failed
    1340                 :             :          * but for that, we might need to clean up the copy state as it might
    1341                 :             :          * be in the middle of fetching the rows. Also, if there is a network
    1342                 :             :          * breakdown then it wouldn't have succeeded so trying it next time
    1343                 :             :          * seems like a better bet.
    1344                 :             :          */
    1345                 :          11 :         ReplicationSlotDropAtPubNode(LogRepWorkerWalRcvConn, slotname, true);
    1346                 :             :     }
    1347         [ -  + ]:         213 :     else if (MyLogicalRepWorker->relstate == SUBREL_STATE_FINISHEDCOPY)
    1348                 :             :     {
    1349                 :             :         /*
    1350                 :             :          * The COPY phase was previously done, but tablesync then crashed
    1351                 :             :          * before it was able to finish normally.
    1352                 :             :          */
    1353                 :           0 :         StartTransactionCommand();
    1354                 :             : 
    1355                 :             :         /*
    1356                 :             :          * The origin tracking name must already exist. It was created first
    1357                 :             :          * time this tablesync was launched.
    1358                 :             :          */
    1359                 :           0 :         originid = replorigin_by_name(originname, false);
    1360                 :           0 :         replorigin_session_setup(originid, 0);
    1361                 :           0 :         replorigin_xact_state.origin = originid;
    1362                 :           0 :         *origin_startpos = replorigin_session_get_progress(false);
    1363                 :             : 
    1364                 :           0 :         CommitTransactionCommand();
    1365                 :             : 
    1366                 :           0 :         goto copy_table_done;
    1367                 :             :     }
    1368                 :             : 
    1369                 :         224 :     SpinLockAcquire(&MyLogicalRepWorker->relmutex);
    1370                 :         224 :     MyLogicalRepWorker->relstate = SUBREL_STATE_DATASYNC;
    1371                 :         224 :     MyLogicalRepWorker->relstate_lsn = InvalidXLogRecPtr;
    1372                 :         224 :     SpinLockRelease(&MyLogicalRepWorker->relmutex);
    1373                 :             : 
    1374                 :             :     /*
    1375                 :             :      * Update the state, create the replication origin, and make them visible
    1376                 :             :      * to others.
    1377                 :             :      */
    1378                 :         224 :     StartTransactionCommand();
    1379                 :         224 :     UpdateSubscriptionRelState(MyLogicalRepWorker->subid,
    1380                 :         224 :                                MyLogicalRepWorker->relid,
    1381                 :         224 :                                MyLogicalRepWorker->relstate,
    1382                 :         224 :                                MyLogicalRepWorker->relstate_lsn,
    1383                 :             :                                false);
    1384                 :             : 
    1385                 :             :     /*
    1386                 :             :      * Create the replication origin in a separate transaction from the one
    1387                 :             :      * that sets up the origin in shared memory. This prevents the risk that
    1388                 :             :      * changes to the origin in shared memory cannot be rolled back if the
    1389                 :             :      * transaction aborts.
    1390                 :             :      */
    1391                 :         224 :     originid = replorigin_by_name(originname, true);
    1392         [ +  + ]:         224 :     if (!OidIsValid(originid))
    1393                 :         213 :         originid = replorigin_create(originname);
    1394                 :             : 
    1395                 :         224 :     CommitTransactionCommand();
    1396                 :         224 :     pgstat_report_stat(true);
    1397                 :             : 
    1398                 :         224 :     StartTransactionCommand();
    1399                 :             : 
    1400                 :             :     /*
    1401                 :             :      * Use a standard write lock here. It might be better to disallow access
    1402                 :             :      * to the table while it's being synchronized. But we don't want to block
    1403                 :             :      * the main apply process from working and it has to open the relation in
    1404                 :             :      * RowExclusiveLock when remapping remote relation id to local one.
    1405                 :             :      */
    1406                 :         224 :     rel = table_open(MyLogicalRepWorker->relid, RowExclusiveLock);
    1407                 :             : 
    1408                 :             :     /*
    1409                 :             :      * Start a transaction in the remote node in REPEATABLE READ mode.  This
    1410                 :             :      * ensures that both the replication slot we create (see below) and the
    1411                 :             :      * COPY are consistent with each other.
    1412                 :             :      */
    1413                 :         224 :     res = walrcv_exec(LogRepWorkerWalRcvConn,
    1414                 :             :                       "BEGIN READ ONLY ISOLATION LEVEL REPEATABLE READ",
    1415                 :             :                       0, NULL);
    1416         [ -  + ]:         224 :     if (res->status != WALRCV_OK_COMMAND)
    1417         [ #  # ]:           0 :         ereport(ERROR,
    1418                 :             :                 (errcode(ERRCODE_CONNECTION_FAILURE),
    1419                 :             :                  errmsg("table copy could not start transaction on publisher: %s",
    1420                 :             :                         res->err)));
    1421                 :         224 :     walrcv_clear_result(res);
    1422                 :             : 
    1423                 :             :     /*
    1424                 :             :      * Create a new permanent logical decoding slot. This slot will be used
    1425                 :             :      * for the catchup phase after COPY is done, so tell it to use the
    1426                 :             :      * snapshot to make the final data consistent.
    1427                 :             :      */
    1428                 :         224 :     walrcv_create_slot(LogRepWorkerWalRcvConn,
    1429                 :             :                        slotname, false /* permanent */ , false /* two_phase */ ,
    1430                 :             :                        MySubscription->failover,
    1431                 :             :                        CRS_USE_SNAPSHOT, origin_startpos);
    1432                 :             : 
    1433                 :             :     /*
    1434                 :             :      * Advance the origin to the LSN got from walrcv_create_slot and then set
    1435                 :             :      * up the origin. The advancement is WAL logged for the purpose of
    1436                 :             :      * recovery. Locks are to prevent the replication origin from vanishing
    1437                 :             :      * while advancing.
    1438                 :             :      *
    1439                 :             :      * The purpose of doing these before the copy is to avoid doing the copy
    1440                 :             :      * again due to any error in advancing or setting up origin tracking.
    1441                 :             :      */
    1442                 :         224 :     LockRelationOid(ReplicationOriginRelationId, RowExclusiveLock);
    1443                 :         224 :     replorigin_advance(originid, *origin_startpos, InvalidXLogRecPtr,
    1444                 :             :                        true /* go backward */ , true /* WAL log */ );
    1445                 :         224 :     UnlockRelationOid(ReplicationOriginRelationId, RowExclusiveLock);
    1446                 :             : 
    1447                 :         224 :     replorigin_session_setup(originid, 0);
    1448                 :         224 :     replorigin_xact_state.origin = originid;
    1449                 :             : 
    1450                 :             :     /*
    1451                 :             :      * If the user did not opt to run as the owner of the subscription
    1452                 :             :      * ('run_as_owner'), then copy the table as the owner of the table.
    1453                 :             :      */
    1454                 :         224 :     run_as_owner = MySubscription->runasowner;
    1455         [ +  + ]:         224 :     if (!run_as_owner)
    1456                 :         223 :         SwitchToUntrustedUser(rel->rd_rel->relowner, &ucxt);
    1457                 :             : 
    1458                 :             :     /*
    1459                 :             :      * Check that our table sync worker has permission to insert into the
    1460                 :             :      * target table.
    1461                 :             :      */
    1462                 :         224 :     aclresult = pg_class_aclcheck(RelationGetRelid(rel), GetUserId(),
    1463                 :             :                                   ACL_INSERT);
    1464         [ -  + ]:         224 :     if (aclresult != ACLCHECK_OK)
    1465                 :           0 :         aclcheck_error(aclresult,
    1466                 :           0 :                        get_relkind_objtype(rel->rd_rel->relkind),
    1467                 :           0 :                        RelationGetRelationName(rel));
    1468                 :             : 
    1469                 :             :     /*
    1470                 :             :      * COPY FROM does not honor RLS policies.  That is not a problem for
    1471                 :             :      * subscriptions owned by roles with BYPASSRLS privilege (or superuser,
    1472                 :             :      * who has it implicitly), but other roles should not be able to
    1473                 :             :      * circumvent RLS.  Disallow logical replication into RLS enabled
    1474                 :             :      * relations for such roles.
    1475                 :             :      */
    1476         [ -  + ]:         224 :     if (check_enable_rls(RelationGetRelid(rel), InvalidOid, false) == RLS_ENABLED)
    1477         [ #  # ]:           0 :         ereport(ERROR,
    1478                 :             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
    1479                 :             :                  errmsg("user \"%s\" cannot replicate into relation with row-level security enabled: \"%s\"",
    1480                 :             :                         GetUserNameFromId(GetUserId(), true),
    1481                 :             :                         RelationGetRelationName(rel))));
    1482                 :             : 
    1483                 :             :     /* Now do the initial data copy */
    1484                 :         224 :     PushActiveSnapshot(GetTransactionSnapshot());
    1485                 :         224 :     copy_table(rel);
    1486                 :         209 :     PopActiveSnapshot();
    1487                 :             : 
    1488                 :         209 :     res = walrcv_exec(LogRepWorkerWalRcvConn, "COMMIT", 0, NULL);
    1489         [ -  + ]:         209 :     if (res->status != WALRCV_OK_COMMAND)
    1490         [ #  # ]:           0 :         ereport(ERROR,
    1491                 :             :                 (errcode(ERRCODE_CONNECTION_FAILURE),
    1492                 :             :                  errmsg("table copy could not finish transaction on publisher: %s",
    1493                 :             :                         res->err)));
    1494                 :         209 :     walrcv_clear_result(res);
    1495                 :             : 
    1496         [ +  + ]:         209 :     if (!run_as_owner)
    1497                 :         208 :         RestoreUserContext(&ucxt);
    1498                 :             : 
    1499                 :         209 :     table_close(rel, NoLock);
    1500                 :             : 
    1501                 :             :     /* Make the copy visible. */
    1502                 :         209 :     CommandCounterIncrement();
    1503                 :             : 
    1504                 :             :     /*
    1505                 :             :      * Update the persisted state to indicate the COPY phase is done; make it
    1506                 :             :      * visible to others.
    1507                 :             :      */
    1508                 :         209 :     UpdateSubscriptionRelState(MyLogicalRepWorker->subid,
    1509                 :         209 :                                MyLogicalRepWorker->relid,
    1510                 :             :                                SUBREL_STATE_FINISHEDCOPY,
    1511                 :         209 :                                MyLogicalRepWorker->relstate_lsn,
    1512                 :             :                                false);
    1513                 :             : 
    1514                 :         209 :     CommitTransactionCommand();
    1515                 :             : 
    1516                 :         209 : copy_table_done:
    1517                 :             : 
    1518         [ -  + ]:         209 :     elog(DEBUG1,
    1519                 :             :          "LogicalRepSyncTableStart: '%s' origin_startpos lsn %X/%08X",
    1520                 :             :          originname, LSN_FORMAT_ARGS(*origin_startpos));
    1521                 :             : 
    1522                 :             :     /*
    1523                 :             :      * We are done with the initial data synchronization, update the state.
    1524                 :             :      */
    1525                 :         209 :     SpinLockAcquire(&MyLogicalRepWorker->relmutex);
    1526                 :         209 :     MyLogicalRepWorker->relstate = SUBREL_STATE_SYNCWAIT;
    1527                 :         209 :     MyLogicalRepWorker->relstate_lsn = *origin_startpos;
    1528                 :         209 :     SpinLockRelease(&MyLogicalRepWorker->relmutex);
    1529                 :             : 
    1530                 :             :     /*
    1531                 :             :      * Finally, wait until the leader apply worker tells us to catch up and
    1532                 :             :      * then return to let LogicalRepApplyLoop do it.
    1533                 :             :      */
    1534                 :         209 :     wait_for_worker_state_change(SUBREL_STATE_CATCHUP);
    1535                 :         209 :     return slotname;
    1536                 :             : }
    1537                 :             : 
    1538                 :             : /*
    1539                 :             :  * Execute the initial sync with error handling. Disable the subscription,
    1540                 :             :  * if it's required.
    1541                 :             :  *
    1542                 :             :  * Allocate the slot name in long-lived context on return. Note that we don't
    1543                 :             :  * handle FATAL errors which are probably because of system resource error and
    1544                 :             :  * are not repeatable.
    1545                 :             :  */
    1546                 :             : static void
    1547                 :         224 : start_table_sync(XLogRecPtr *origin_startpos, char **slotname)
    1548                 :             : {
    1549                 :         224 :     char       *sync_slotname = NULL;
    1550                 :             : 
    1551                 :             :     Assert(am_tablesync_worker());
    1552                 :             : 
    1553         [ +  + ]:         224 :     PG_TRY();
    1554                 :             :     {
    1555                 :             :         /* Call initial sync. */
    1556                 :         224 :         sync_slotname = LogicalRepSyncTableStart(origin_startpos);
    1557                 :             :     }
    1558                 :          15 :     PG_CATCH();
    1559                 :             :     {
    1560         [ +  + ]:          15 :         if (MySubscription->disableonerr)
    1561                 :           1 :             DisableSubscriptionAndExit();
    1562                 :             :         else
    1563                 :             :         {
    1564                 :             :             /*
    1565                 :             :              * Report the worker failed during table synchronization. Abort
    1566                 :             :              * the current transaction so that the stats message is sent in an
    1567                 :             :              * idle state.
    1568                 :             :              */
    1569                 :          14 :             AbortOutOfAnyTransaction();
    1570                 :          14 :             pgstat_report_subscription_error(MySubscription->oid);
    1571                 :             : 
    1572                 :          14 :             PG_RE_THROW();
    1573                 :             :         }
    1574                 :             :     }
    1575         [ -  + ]:         209 :     PG_END_TRY();
    1576                 :             : 
    1577                 :             :     /* allocate slot name in long-lived context */
    1578                 :         209 :     *slotname = MemoryContextStrdup(ApplyContext, sync_slotname);
    1579                 :         209 :     pfree(sync_slotname);
    1580                 :         209 : }
    1581                 :             : 
    1582                 :             : /*
    1583                 :             :  * Runs the tablesync worker.
    1584                 :             :  *
    1585                 :             :  * It starts syncing tables. After a successful sync, sets streaming options
    1586                 :             :  * and starts streaming to catchup with apply worker.
    1587                 :             :  */
    1588                 :             : static void
    1589                 :         224 : run_tablesync_worker(void)
    1590                 :             : {
    1591                 :             :     char        originname[NAMEDATALEN];
    1592                 :         224 :     XLogRecPtr  origin_startpos = InvalidXLogRecPtr;
    1593                 :         224 :     char       *slotname = NULL;
    1594                 :             :     WalRcvStreamOptions options;
    1595                 :             : 
    1596                 :         224 :     start_table_sync(&origin_startpos, &slotname);
    1597                 :             : 
    1598                 :         209 :     ReplicationOriginNameForLogicalRep(MySubscription->oid,
    1599                 :         209 :                                        MyLogicalRepWorker->relid,
    1600                 :             :                                        originname,
    1601                 :             :                                        sizeof(originname));
    1602                 :             : 
    1603                 :         209 :     set_apply_error_context_origin(originname);
    1604                 :             : 
    1605                 :         209 :     set_stream_options(&options, slotname, &origin_startpos);
    1606                 :             : 
    1607                 :         209 :     walrcv_startstreaming(LogRepWorkerWalRcvConn, &options);
    1608                 :             : 
    1609                 :             :     /* Apply the changes till we catchup with the apply worker. */
    1610                 :         209 :     start_apply(origin_startpos);
    1611                 :           0 : }
    1612                 :             : 
    1613                 :             : /* Logical Replication Tablesync worker entry point */
    1614                 :             : void
    1615                 :         225 : TableSyncWorkerMain(Datum main_arg)
    1616                 :             : {
    1617                 :         225 :     int         worker_slot = DatumGetInt32(main_arg);
    1618                 :             : 
    1619                 :         225 :     SetupApplyOrSyncWorker(worker_slot);
    1620                 :             : 
    1621                 :         224 :     run_tablesync_worker();
    1622                 :             : 
    1623                 :           0 :     FinishSyncWorker();
    1624                 :             : }
    1625                 :             : 
    1626                 :             : /*
    1627                 :             :  * If the subscription has no tables then return false.
    1628                 :             :  *
    1629                 :             :  * Otherwise, are all tablesyncs READY?
    1630                 :             :  *
    1631                 :             :  * Note: This function is not suitable to be called from outside of apply or
    1632                 :             :  * tablesync workers because MySubscription needs to be already initialized.
    1633                 :             :  */
    1634                 :             : bool
    1635                 :         298 : AllTablesyncsReady(void)
    1636                 :             : {
    1637                 :             :     bool        started_tx;
    1638                 :             :     bool        has_tables;
    1639                 :             : 
    1640                 :             :     /* We need up-to-date sync state info for subscription tables here. */
    1641                 :         298 :     FetchRelationStates(&has_tables, NULL, &started_tx);
    1642                 :             : 
    1643         [ +  + ]:         298 :     if (started_tx)
    1644                 :             :     {
    1645                 :          19 :         CommitTransactionCommand();
    1646                 :          19 :         pgstat_report_stat(true);
    1647                 :             :     }
    1648                 :             : 
    1649                 :             :     /*
    1650                 :             :      * Return false when there are no tables in subscription or not all tables
    1651                 :             :      * are in ready state; true otherwise.
    1652                 :             :      */
    1653   [ +  -  +  + ]:         298 :     return has_tables && (table_states_not_ready == NIL);
    1654                 :             : }
    1655                 :             : 
    1656                 :             : /*
    1657                 :             :  * Return whether the subscription currently has any tables.
    1658                 :             :  *
    1659                 :             :  * Note: Unlike HasSubscriptionTables(), this function relies on cached
    1660                 :             :  * information for subscription tables. Additionally, it should not be
    1661                 :             :  * invoked outside of apply or tablesync workers, as MySubscription must be
    1662                 :             :  * initialized first.
    1663                 :             :  */
    1664                 :             : bool
    1665                 :         212 : HasSubscriptionTablesCached(void)
    1666                 :             : {
    1667                 :             :     bool        started_tx;
    1668                 :             :     bool        has_tables;
    1669                 :             : 
    1670                 :             :     /* We need up-to-date subscription tables info here */
    1671                 :         212 :     FetchRelationStates(&has_tables, NULL, &started_tx);
    1672                 :             : 
    1673         [ -  + ]:         212 :     if (started_tx)
    1674                 :             :     {
    1675                 :           0 :         CommitTransactionCommand();
    1676                 :           0 :         pgstat_report_stat(true);
    1677                 :             :     }
    1678                 :             : 
    1679                 :         212 :     return has_tables;
    1680                 :             : }
    1681                 :             : 
    1682                 :             : /*
    1683                 :             :  * Update the two_phase state of the specified subscription in pg_subscription.
    1684                 :             :  */
    1685                 :             : void
    1686                 :          11 : UpdateTwoPhaseState(Oid suboid, char new_state)
    1687                 :             : {
    1688                 :             :     Relation    rel;
    1689                 :             :     HeapTuple   tup;
    1690                 :             :     bool        nulls[Natts_pg_subscription];
    1691                 :             :     bool        replaces[Natts_pg_subscription];
    1692                 :             :     Datum       values[Natts_pg_subscription];
    1693                 :             : 
    1694                 :             :     Assert(new_state == LOGICALREP_TWOPHASE_STATE_DISABLED ||
    1695                 :             :            new_state == LOGICALREP_TWOPHASE_STATE_PENDING ||
    1696                 :             :            new_state == LOGICALREP_TWOPHASE_STATE_ENABLED);
    1697                 :             : 
    1698                 :          11 :     rel = table_open(SubscriptionRelationId, RowExclusiveLock);
    1699                 :          11 :     tup = SearchSysCacheCopy1(SUBSCRIPTIONOID, ObjectIdGetDatum(suboid));
    1700         [ -  + ]:          11 :     if (!HeapTupleIsValid(tup))
    1701         [ #  # ]:           0 :         elog(ERROR,
    1702                 :             :              "cache lookup failed for subscription oid %u",
    1703                 :             :              suboid);
    1704                 :             : 
    1705                 :             :     /* Form a new tuple. */
    1706                 :          11 :     memset(values, 0, sizeof(values));
    1707                 :          11 :     memset(nulls, false, sizeof(nulls));
    1708                 :          11 :     memset(replaces, false, sizeof(replaces));
    1709                 :             : 
    1710                 :             :     /* And update/set two_phase state */
    1711                 :          11 :     values[Anum_pg_subscription_subtwophasestate - 1] = CharGetDatum(new_state);
    1712                 :          11 :     replaces[Anum_pg_subscription_subtwophasestate - 1] = true;
    1713                 :             : 
    1714                 :          11 :     tup = heap_modify_tuple(tup, RelationGetDescr(rel),
    1715                 :             :                             values, nulls, replaces);
    1716                 :          11 :     CatalogTupleUpdate(rel, &tup->t_self, tup);
    1717                 :             : 
    1718                 :          11 :     heap_freetuple(tup);
    1719                 :          11 :     table_close(rel, RowExclusiveLock);
    1720                 :          11 : }
        

Generated by: LCOV version 2.0-1