PostgreSQL Source Code  git master
tablesync.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  * tablesync.c
3  * PostgreSQL logical replication: initial table data synchronization
4  *
5  * Copyright (c) 2012-2023, 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"
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"
110 #include "replication/walreceiver.h"
112 #include "replication/slot.h"
113 #include "replication/origin.h"
114 #include "storage/ipc.h"
115 #include "storage/lmgr.h"
116 #include "utils/acl.h"
117 #include "utils/array.h"
118 #include "utils/builtins.h"
119 #include "utils/lsyscache.h"
120 #include "utils/memutils.h"
121 #include "utils/rls.h"
122 #include "utils/snapmgr.h"
123 #include "utils/syscache.h"
124 #include "utils/usercontext.h"
125 
126 static bool table_states_valid = false;
128 static bool FetchTableStates(bool *started_tx);
129 
130 static StringInfo copybuf = NULL;
131 
132 /*
133  * Exit routine for synchronization worker.
134  */
135 static void
137 finish_sync_worker(void)
138 {
139  /*
140  * Commit any outstanding transaction. This is the usual case, unless
141  * there was nothing to do for the table.
142  */
143  if (IsTransactionState())
144  {
146  pgstat_report_stat(true);
147  }
148 
149  /* And flush all writes. */
151 
153  ereport(LOG,
154  (errmsg("logical replication table synchronization worker for subscription \"%s\", table \"%s\" has finished",
158 
159  /* Find the leader apply worker and signal it. */
161 
162  /* Stop gracefully */
163  proc_exit(0);
164 }
165 
166 /*
167  * Wait until the relation sync state is set in the catalog to the expected
168  * one; return true when it happens.
169  *
170  * Returns false if the table sync worker or the table itself have
171  * disappeared, or the table state has been reset.
172  *
173  * Currently, this is used in the apply worker when transitioning from
174  * CATCHUP state to SYNCDONE.
175  */
176 static bool
177 wait_for_relation_state_change(Oid relid, char expected_state)
178 {
179  char state;
180 
181  for (;;)
182  {
183  LogicalRepWorker *worker;
184  XLogRecPtr statelsn;
185 
187 
190  relid, &statelsn);
191 
192  if (state == SUBREL_STATE_UNKNOWN)
193  break;
194 
195  if (state == expected_state)
196  return true;
197 
198  /* Check if the sync worker is still running and bail if not. */
199  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
201  false);
202  LWLockRelease(LogicalRepWorkerLock);
203  if (!worker)
204  break;
205 
206  (void) WaitLatch(MyLatch,
208  1000L, WAIT_EVENT_LOGICAL_SYNC_STATE_CHANGE);
209 
211  }
212 
213  return false;
214 }
215 
216 /*
217  * Wait until the apply worker changes the state of our synchronization
218  * worker to the expected one.
219  *
220  * Used when transitioning from SYNCWAIT state to CATCHUP.
221  *
222  * Returns false if the apply worker has disappeared.
223  */
224 static bool
225 wait_for_worker_state_change(char expected_state)
226 {
227  int rc;
228 
229  for (;;)
230  {
231  LogicalRepWorker *worker;
232 
234 
235  /*
236  * Done if already in correct state. (We assume this fetch is atomic
237  * enough to not give a misleading answer if we do it with no lock.)
238  */
239  if (MyLogicalRepWorker->relstate == expected_state)
240  return true;
241 
242  /*
243  * Bail out if the apply worker has died, else signal it we're
244  * waiting.
245  */
246  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
248  InvalidOid, false);
249  if (worker && worker->proc)
251  LWLockRelease(LogicalRepWorkerLock);
252  if (!worker)
253  break;
254 
255  /*
256  * Wait. We expect to get a latch signal back from the apply worker,
257  * but use a timeout in case it dies without sending one.
258  */
259  rc = WaitLatch(MyLatch,
261  1000L, WAIT_EVENT_LOGICAL_SYNC_STATE_CHANGE);
262 
263  if (rc & WL_LATCH_SET)
265  }
266 
267  return false;
268 }
269 
270 /*
271  * Callback from syscache invalidation.
272  */
273 void
275 {
276  table_states_valid = false;
277 }
278 
279 /*
280  * Handle table synchronization cooperation from the synchronization
281  * worker.
282  *
283  * If the sync worker is in CATCHUP state and reached (or passed) the
284  * predetermined synchronization point in the WAL stream, mark the table as
285  * SYNCDONE and finish.
286  */
287 static void
289 {
291 
292  if (MyLogicalRepWorker->relstate == SUBREL_STATE_CATCHUP &&
293  current_lsn >= MyLogicalRepWorker->relstate_lsn)
294  {
295  TimeLineID tli;
296  char syncslotname[NAMEDATALEN] = {0};
297  char originname[NAMEDATALEN] = {0};
298 
299  MyLogicalRepWorker->relstate = SUBREL_STATE_SYNCDONE;
300  MyLogicalRepWorker->relstate_lsn = current_lsn;
301 
303 
304  /*
305  * UpdateSubscriptionRelState must be called within a transaction.
306  */
307  if (!IsTransactionState())
309 
314 
315  /*
316  * End streaming so that LogRepWorkerWalRcvConn can be used to drop
317  * the slot.
318  */
320 
321  /*
322  * Cleanup the tablesync slot.
323  *
324  * This has to be done after updating the state because otherwise if
325  * there is an error while doing the database operations we won't be
326  * able to rollback dropped slot.
327  */
330  syncslotname,
331  sizeof(syncslotname));
332 
333  /*
334  * It is important to give an error if we are unable to drop the slot,
335  * otherwise, it won't be dropped till the corresponding subscription
336  * is dropped. So passing missing_ok = false.
337  */
339 
341  pgstat_report_stat(false);
342 
343  /*
344  * Start a new transaction to clean up the tablesync origin tracking.
345  * This transaction will be ended within the finish_sync_worker().
346  * Now, even, if we fail to remove this here, the apply worker will
347  * ensure to clean it up afterward.
348  *
349  * We need to do this after the table state is set to SYNCDONE.
350  * Otherwise, if an error occurs while performing the database
351  * operation, the worker will be restarted and the in-memory state of
352  * replication progress (remote_lsn) won't be rolled-back which would
353  * have been cleared before restart. So, the restarted worker will use
354  * invalid replication progress state resulting in replay of
355  * transactions that have already been applied.
356  */
358 
361  originname,
362  sizeof(originname));
363 
364  /*
365  * Resetting the origin session removes the ownership of the slot.
366  * This is needed to allow the origin to be dropped.
367  */
372 
373  /*
374  * Drop the tablesync's origin tracking if exists.
375  *
376  * There is a chance that the user is concurrently performing refresh
377  * for the subscription where we remove the table state and its origin
378  * or the apply worker would have removed this origin. So passing
379  * missing_ok = true.
380  */
381  replorigin_drop_by_name(originname, true, false);
382 
383  finish_sync_worker();
384  }
385  else
387 }
388 
389 /*
390  * Handle table synchronization cooperation from the apply worker.
391  *
392  * Walk over all subscription tables that are individually tracked by the
393  * apply process (currently, all that have state other than
394  * SUBREL_STATE_READY) and manage synchronization for them.
395  *
396  * If there are tables that need synchronizing and are not being synchronized
397  * yet, start sync workers for them (if there are free slots for sync
398  * workers). To prevent starting the sync worker for the same relation at a
399  * high frequency after a failure, we store its last start time with each sync
400  * state info. We start the sync worker for the same relation after waiting
401  * at least wal_retrieve_retry_interval.
402  *
403  * For tables that are being synchronized already, check if sync workers
404  * either need action from the apply worker or have finished. This is the
405  * SYNCWAIT to CATCHUP transition.
406  *
407  * If the synchronization position is reached (SYNCDONE), then the table can
408  * be marked as READY and is no longer tracked.
409  */
410 static void
412 {
413  struct tablesync_start_time_mapping
414  {
415  Oid relid;
416  TimestampTz last_start_time;
417  };
418  static HTAB *last_start_times = NULL;
419  ListCell *lc;
420  bool started_tx = false;
421  bool should_exit = false;
422 
424 
425  /* We need up-to-date sync state info for subscription tables here. */
426  FetchTableStates(&started_tx);
427 
428  /*
429  * Prepare a hash table for tracking last start times of workers, to avoid
430  * immediate restarts. We don't need it if there are no tables that need
431  * syncing.
432  */
434  {
435  HASHCTL ctl;
436 
437  ctl.keysize = sizeof(Oid);
438  ctl.entrysize = sizeof(struct tablesync_start_time_mapping);
439  last_start_times = hash_create("Logical replication table sync worker start times",
440  256, &ctl, HASH_ELEM | HASH_BLOBS);
441  }
442 
443  /*
444  * Clean up the hash table when we're done with all tables (just to
445  * release the bit of memory).
446  */
448  {
450  last_start_times = NULL;
451  }
452 
453  /*
454  * Process all tables that are being synchronized.
455  */
456  foreach(lc, table_states_not_ready)
457  {
459 
460  if (rstate->state == SUBREL_STATE_SYNCDONE)
461  {
462  /*
463  * Apply has caught up to the position where the table sync has
464  * finished. Mark the table as ready so that the apply will just
465  * continue to replicate it normally.
466  */
467  if (current_lsn >= rstate->lsn)
468  {
469  char originname[NAMEDATALEN];
470 
471  rstate->state = SUBREL_STATE_READY;
472  rstate->lsn = current_lsn;
473  if (!started_tx)
474  {
476  started_tx = true;
477  }
478 
479  /*
480  * Remove the tablesync origin tracking if exists.
481  *
482  * There is a chance that the user is concurrently performing
483  * refresh for the subscription where we remove the table
484  * state and its origin or the tablesync worker would have
485  * already removed this origin. We can't rely on tablesync
486  * worker to remove the origin tracking as if there is any
487  * error while dropping we won't restart it to drop the
488  * origin. So passing missing_ok = true.
489  */
491  rstate->relid,
492  originname,
493  sizeof(originname));
494  replorigin_drop_by_name(originname, true, false);
495 
496  /*
497  * Update the state to READY only after the origin cleanup.
498  */
500  rstate->relid, rstate->state,
501  rstate->lsn);
502  }
503  }
504  else
505  {
506  LogicalRepWorker *syncworker;
507 
508  /*
509  * Look for a sync worker for this relation.
510  */
511  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
512 
514  rstate->relid, false);
515 
516  if (syncworker)
517  {
518  /* Found one, update our copy of its state */
519  SpinLockAcquire(&syncworker->relmutex);
520  rstate->state = syncworker->relstate;
521  rstate->lsn = syncworker->relstate_lsn;
522  if (rstate->state == SUBREL_STATE_SYNCWAIT)
523  {
524  /*
525  * Sync worker is waiting for apply. Tell sync worker it
526  * can catchup now.
527  */
528  syncworker->relstate = SUBREL_STATE_CATCHUP;
529  syncworker->relstate_lsn =
530  Max(syncworker->relstate_lsn, current_lsn);
531  }
532  SpinLockRelease(&syncworker->relmutex);
533 
534  /* If we told worker to catch up, wait for it. */
535  if (rstate->state == SUBREL_STATE_SYNCWAIT)
536  {
537  /* Signal the sync worker, as it may be waiting for us. */
538  if (syncworker->proc)
539  logicalrep_worker_wakeup_ptr(syncworker);
540 
541  /* Now safe to release the LWLock */
542  LWLockRelease(LogicalRepWorkerLock);
543 
544  /*
545  * Enter busy loop and wait for synchronization worker to
546  * reach expected state (or die trying).
547  */
548  if (!started_tx)
549  {
551  started_tx = true;
552  }
553 
555  SUBREL_STATE_SYNCDONE);
556  }
557  else
558  LWLockRelease(LogicalRepWorkerLock);
559  }
560  else
561  {
562  /*
563  * If there is no sync worker for this table yet, count
564  * running sync workers for this subscription, while we have
565  * the lock.
566  */
567  int nsyncworkers =
569 
570  /* Now safe to release the LWLock */
571  LWLockRelease(LogicalRepWorkerLock);
572 
573  /*
574  * If there are free sync worker slot(s), start a new sync
575  * worker for the table.
576  */
577  if (nsyncworkers < max_sync_workers_per_subscription)
578  {
580  struct tablesync_start_time_mapping *hentry;
581  bool found;
582 
583  hentry = hash_search(last_start_times, &rstate->relid,
584  HASH_ENTER, &found);
585 
586  if (!found ||
587  TimestampDifferenceExceeds(hentry->last_start_time, now,
589  {
595  rstate->relid,
597  hentry->last_start_time = now;
598  }
599  }
600  }
601  }
602  }
603 
604  if (started_tx)
605  {
606  /*
607  * Even when the two_phase mode is requested by the user, it remains
608  * as 'pending' until all tablesyncs have reached READY state.
609  *
610  * When this happens, we restart the apply worker and (if the
611  * conditions are still ok) then the two_phase tri-state will become
612  * 'enabled' at that time.
613  *
614  * Note: If the subscription has no tables then leave the state as
615  * PENDING, which allows ALTER SUBSCRIPTION ... REFRESH PUBLICATION to
616  * work.
617  */
619  {
620  CommandCounterIncrement(); /* make updates visible */
621  if (AllTablesyncsReady())
622  {
623  ereport(LOG,
624  (errmsg("logical replication apply worker for subscription \"%s\" will restart so that two_phase can be enabled",
625  MySubscription->name)));
626  should_exit = true;
627  }
628  }
629 
631  pgstat_report_stat(true);
632  }
633 
634  if (should_exit)
635  {
636  /*
637  * Reset the last-start time for this worker so that the launcher will
638  * restart it without waiting for wal_retrieve_retry_interval.
639  */
641 
642  proc_exit(0);
643  }
644 }
645 
646 /*
647  * Process possible state change(s) of tables that are being synchronized.
648  */
649 void
651 {
652  switch (MyLogicalRepWorker->type)
653  {
655 
656  /*
657  * Skip for parallel apply workers because they only operate on
658  * tables that are in a READY state. See pa_can_start() and
659  * should_apply_changes_for_rel().
660  */
661  break;
662 
664  process_syncing_tables_for_sync(current_lsn);
665  break;
666 
667  case WORKERTYPE_APPLY:
669  break;
670 
671  case WORKERTYPE_UNKNOWN:
672  /* Should never happen. */
673  elog(ERROR, "Unknown worker type");
674  }
675 }
676 
677 /*
678  * Create list of columns for COPY based on logical relation mapping.
679  */
680 static List *
682 {
683  List *attnamelist = NIL;
684  int i;
685 
686  for (i = 0; i < rel->remoterel.natts; i++)
687  {
688  attnamelist = lappend(attnamelist,
689  makeString(rel->remoterel.attnames[i]));
690  }
691 
692 
693  return attnamelist;
694 }
695 
696 /*
697  * Data source callback for the COPY FROM, which reads from the remote
698  * connection and passes the data back to our local COPY.
699  */
700 static int
701 copy_read_data(void *outbuf, int minread, int maxread)
702 {
703  int bytesread = 0;
704  int avail;
705 
706  /* If there are some leftover data from previous read, use it. */
707  avail = copybuf->len - copybuf->cursor;
708  if (avail)
709  {
710  if (avail > maxread)
711  avail = maxread;
712  memcpy(outbuf, &copybuf->data[copybuf->cursor], avail);
713  copybuf->cursor += avail;
714  maxread -= avail;
715  bytesread += avail;
716  }
717 
718  while (maxread > 0 && bytesread < minread)
719  {
721  int len;
722  char *buf = NULL;
723 
724  for (;;)
725  {
726  /* Try read the data. */
728 
730 
731  if (len == 0)
732  break;
733  else if (len < 0)
734  return bytesread;
735  else
736  {
737  /* Process the data */
738  copybuf->data = buf;
739  copybuf->len = len;
740  copybuf->cursor = 0;
741 
742  avail = copybuf->len - copybuf->cursor;
743  if (avail > maxread)
744  avail = maxread;
745  memcpy(outbuf, &copybuf->data[copybuf->cursor], avail);
746  outbuf = (void *) ((char *) outbuf + avail);
747  copybuf->cursor += avail;
748  maxread -= avail;
749  bytesread += avail;
750  }
751 
752  if (maxread <= 0 || bytesread >= minread)
753  return bytesread;
754  }
755 
756  /*
757  * Wait for more data or latch.
758  */
759  (void) WaitLatchOrSocket(MyLatch,
762  fd, 1000L, WAIT_EVENT_LOGICAL_SYNC_DATA);
763 
765  }
766 
767  return bytesread;
768 }
769 
770 
771 /*
772  * Get information about remote relation in similar fashion the RELATION
773  * message provides during replication. This function also returns the relation
774  * qualifications to be used in the COPY command.
775  */
776 static void
777 fetch_remote_table_info(char *nspname, char *relname,
778  LogicalRepRelation *lrel, List **qual)
779 {
781  StringInfoData cmd;
782  TupleTableSlot *slot;
783  Oid tableRow[] = {OIDOID, CHAROID, CHAROID};
784  Oid attrRow[] = {INT2OID, TEXTOID, OIDOID, BOOLOID};
785  Oid qualRow[] = {TEXTOID};
786  bool isnull;
787  int natt;
788  ListCell *lc;
789  Bitmapset *included_cols = NULL;
790 
791  lrel->nspname = nspname;
792  lrel->relname = relname;
793 
794  /* First fetch Oid and replica identity. */
795  initStringInfo(&cmd);
796  appendStringInfo(&cmd, "SELECT c.oid, c.relreplident, c.relkind"
797  " FROM pg_catalog.pg_class c"
798  " INNER JOIN pg_catalog.pg_namespace n"
799  " ON (c.relnamespace = n.oid)"
800  " WHERE n.nspname = %s"
801  " AND c.relname = %s",
802  quote_literal_cstr(nspname),
805  lengthof(tableRow), tableRow);
806 
807  if (res->status != WALRCV_OK_TUPLES)
808  ereport(ERROR,
809  (errcode(ERRCODE_CONNECTION_FAILURE),
810  errmsg("could not fetch table info for table \"%s.%s\" from publisher: %s",
811  nspname, relname, res->err)));
812 
813  slot = MakeSingleTupleTableSlot(res->tupledesc, &TTSOpsMinimalTuple);
814  if (!tuplestore_gettupleslot(res->tuplestore, true, false, slot))
815  ereport(ERROR,
816  (errcode(ERRCODE_UNDEFINED_OBJECT),
817  errmsg("table \"%s.%s\" not found on publisher",
818  nspname, relname)));
819 
820  lrel->remoteid = DatumGetObjectId(slot_getattr(slot, 1, &isnull));
821  Assert(!isnull);
822  lrel->replident = DatumGetChar(slot_getattr(slot, 2, &isnull));
823  Assert(!isnull);
824  lrel->relkind = DatumGetChar(slot_getattr(slot, 3, &isnull));
825  Assert(!isnull);
826 
829 
830 
831  /*
832  * Get column lists for each relation.
833  *
834  * We need to do this before fetching info about column names and types,
835  * so that we can skip columns that should not be replicated.
836  */
838  {
839  WalRcvExecResult *pubres;
840  TupleTableSlot *tslot;
841  Oid attrsRow[] = {INT2VECTOROID};
842  StringInfoData pub_names;
843 
844  initStringInfo(&pub_names);
845  foreach(lc, MySubscription->publications)
846  {
847  if (foreach_current_index(lc) > 0)
848  appendStringInfoString(&pub_names, ", ");
850  }
851 
852  /*
853  * Fetch info about column lists for the relation (from all the
854  * publications).
855  */
856  resetStringInfo(&cmd);
857  appendStringInfo(&cmd,
858  "SELECT DISTINCT"
859  " (CASE WHEN (array_length(gpt.attrs, 1) = c.relnatts)"
860  " THEN NULL ELSE gpt.attrs END)"
861  " FROM pg_publication p,"
862  " LATERAL pg_get_publication_tables(p.pubname) gpt,"
863  " pg_class c"
864  " WHERE gpt.relid = %u AND c.oid = gpt.relid"
865  " AND p.pubname IN ( %s )",
866  lrel->remoteid,
867  pub_names.data);
868 
870  lengthof(attrsRow), attrsRow);
871 
872  if (pubres->status != WALRCV_OK_TUPLES)
873  ereport(ERROR,
874  (errcode(ERRCODE_CONNECTION_FAILURE),
875  errmsg("could not fetch column list info for table \"%s.%s\" from publisher: %s",
876  nspname, relname, pubres->err)));
877 
878  /*
879  * We don't support the case where the column list is different for
880  * the same table when combining publications. See comments atop
881  * fetch_table_list. So there should be only one row returned.
882  * Although we already checked this when creating the subscription, we
883  * still need to check here in case the column list was changed after
884  * creating the subscription and before the sync worker is started.
885  */
886  if (tuplestore_tuple_count(pubres->tuplestore) > 1)
887  ereport(ERROR,
888  errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
889  errmsg("cannot use different column lists for table \"%s.%s\" in different publications",
890  nspname, relname));
891 
892  /*
893  * Get the column list and build a single bitmap with the attnums.
894  *
895  * If we find a NULL value, it means all the columns should be
896  * replicated.
897  */
899  if (tuplestore_gettupleslot(pubres->tuplestore, true, false, tslot))
900  {
901  Datum cfval = slot_getattr(tslot, 1, &isnull);
902 
903  if (!isnull)
904  {
905  ArrayType *arr;
906  int nelems;
907  int16 *elems;
908 
909  arr = DatumGetArrayTypeP(cfval);
910  nelems = ARR_DIMS(arr)[0];
911  elems = (int16 *) ARR_DATA_PTR(arr);
912 
913  for (natt = 0; natt < nelems; natt++)
914  included_cols = bms_add_member(included_cols, elems[natt]);
915  }
916 
917  ExecClearTuple(tslot);
918  }
920 
921  walrcv_clear_result(pubres);
922 
923  pfree(pub_names.data);
924  }
925 
926  /*
927  * Now fetch column names and types.
928  */
929  resetStringInfo(&cmd);
930  appendStringInfo(&cmd,
931  "SELECT a.attnum,"
932  " a.attname,"
933  " a.atttypid,"
934  " a.attnum = ANY(i.indkey)"
935  " FROM pg_catalog.pg_attribute a"
936  " LEFT JOIN pg_catalog.pg_index i"
937  " ON (i.indexrelid = pg_get_replica_identity_index(%u))"
938  " WHERE a.attnum > 0::pg_catalog.int2"
939  " AND NOT a.attisdropped %s"
940  " AND a.attrelid = %u"
941  " ORDER BY a.attnum",
942  lrel->remoteid,
944  "AND a.attgenerated = ''" : ""),
945  lrel->remoteid);
947  lengthof(attrRow), attrRow);
948 
949  if (res->status != WALRCV_OK_TUPLES)
950  ereport(ERROR,
951  (errcode(ERRCODE_CONNECTION_FAILURE),
952  errmsg("could not fetch table info for table \"%s.%s\" from publisher: %s",
953  nspname, relname, res->err)));
954 
955  /* We don't know the number of rows coming, so allocate enough space. */
956  lrel->attnames = palloc0(MaxTupleAttributeNumber * sizeof(char *));
957  lrel->atttyps = palloc0(MaxTupleAttributeNumber * sizeof(Oid));
958  lrel->attkeys = NULL;
959 
960  /*
961  * Store the columns as a list of names. Ignore those that are not
962  * present in the column list, if there is one.
963  */
964  natt = 0;
965  slot = MakeSingleTupleTableSlot(res->tupledesc, &TTSOpsMinimalTuple);
966  while (tuplestore_gettupleslot(res->tuplestore, true, false, slot))
967  {
968  char *rel_colname;
970 
971  attnum = DatumGetInt16(slot_getattr(slot, 1, &isnull));
972  Assert(!isnull);
973 
974  /* If the column is not in the column list, skip it. */
975  if (included_cols != NULL && !bms_is_member(attnum, included_cols))
976  {
977  ExecClearTuple(slot);
978  continue;
979  }
980 
981  rel_colname = TextDatumGetCString(slot_getattr(slot, 2, &isnull));
982  Assert(!isnull);
983 
984  lrel->attnames[natt] = rel_colname;
985  lrel->atttyps[natt] = DatumGetObjectId(slot_getattr(slot, 3, &isnull));
986  Assert(!isnull);
987 
988  if (DatumGetBool(slot_getattr(slot, 4, &isnull)))
989  lrel->attkeys = bms_add_member(lrel->attkeys, natt);
990 
991  /* Should never happen. */
992  if (++natt >= MaxTupleAttributeNumber)
993  elog(ERROR, "too many columns in remote table \"%s.%s\"",
994  nspname, relname);
995 
996  ExecClearTuple(slot);
997  }
999 
1000  lrel->natts = natt;
1001 
1003 
1004  /*
1005  * Get relation's row filter expressions. DISTINCT avoids the same
1006  * expression of a table in multiple publications from being included
1007  * multiple times in the final expression.
1008  *
1009  * We need to copy the row even if it matches just one of the
1010  * publications, so we later combine all the quals with OR.
1011  *
1012  * For initial synchronization, row filtering can be ignored in following
1013  * cases:
1014  *
1015  * 1) one of the subscribed publications for the table hasn't specified
1016  * any row filter
1017  *
1018  * 2) one of the subscribed publications has puballtables set to true
1019  *
1020  * 3) one of the subscribed publications is declared as TABLES IN SCHEMA
1021  * that includes this relation
1022  */
1024  {
1025  StringInfoData pub_names;
1026 
1027  /* Build the pubname list. */
1028  initStringInfo(&pub_names);
1029  foreach(lc, MySubscription->publications)
1030  {
1031  char *pubname = strVal(lfirst(lc));
1032 
1033  if (foreach_current_index(lc) > 0)
1034  appendStringInfoString(&pub_names, ", ");
1035 
1036  appendStringInfoString(&pub_names, quote_literal_cstr(pubname));
1037  }
1038 
1039  /* Check for row filters. */
1040  resetStringInfo(&cmd);
1041  appendStringInfo(&cmd,
1042  "SELECT DISTINCT pg_get_expr(gpt.qual, gpt.relid)"
1043  " FROM pg_publication p,"
1044  " LATERAL pg_get_publication_tables(p.pubname) gpt"
1045  " WHERE gpt.relid = %u"
1046  " AND p.pubname IN ( %s )",
1047  lrel->remoteid,
1048  pub_names.data);
1049 
1050  res = walrcv_exec(LogRepWorkerWalRcvConn, cmd.data, 1, qualRow);
1051 
1052  if (res->status != WALRCV_OK_TUPLES)
1053  ereport(ERROR,
1054  (errmsg("could not fetch table WHERE clause info for table \"%s.%s\" from publisher: %s",
1055  nspname, relname, res->err)));
1056 
1057  /*
1058  * Multiple row filter expressions for the same table will be combined
1059  * by COPY using OR. If any of the filter expressions for this table
1060  * are null, it means the whole table will be copied. In this case it
1061  * is not necessary to construct a unified row filter expression at
1062  * all.
1063  */
1064  slot = MakeSingleTupleTableSlot(res->tupledesc, &TTSOpsMinimalTuple);
1065  while (tuplestore_gettupleslot(res->tuplestore, true, false, slot))
1066  {
1067  Datum rf = slot_getattr(slot, 1, &isnull);
1068 
1069  if (!isnull)
1070  *qual = lappend(*qual, makeString(TextDatumGetCString(rf)));
1071  else
1072  {
1073  /* Ignore filters and cleanup as necessary. */
1074  if (*qual)
1075  {
1076  list_free_deep(*qual);
1077  *qual = NIL;
1078  }
1079  break;
1080  }
1081 
1082  ExecClearTuple(slot);
1083  }
1085 
1087  }
1088 
1089  pfree(cmd.data);
1090 }
1091 
1092 /*
1093  * Copy existing data of a table from publisher.
1094  *
1095  * Caller is responsible for locking the local relation.
1096  */
1097 static void
1099 {
1100  LogicalRepRelMapEntry *relmapentry;
1101  LogicalRepRelation lrel;
1102  List *qual = NIL;
1104  StringInfoData cmd;
1105  CopyFromState cstate;
1106  List *attnamelist;
1107  ParseState *pstate;
1108  List *options = NIL;
1109 
1110  /* Get the publisher relation info. */
1112  RelationGetRelationName(rel), &lrel, &qual);
1113 
1114  /* Put the relation into relmap. */
1115  logicalrep_relmap_update(&lrel);
1116 
1117  /* Map the publisher relation to local one. */
1118  relmapentry = logicalrep_rel_open(lrel.remoteid, NoLock);
1119  Assert(rel == relmapentry->localrel);
1120 
1121  /* Start copy on the publisher. */
1122  initStringInfo(&cmd);
1123 
1124  /* Regular table with no row filter */
1125  if (lrel.relkind == RELKIND_RELATION && qual == NIL)
1126  {
1127  appendStringInfo(&cmd, "COPY %s (",
1129 
1130  /*
1131  * XXX Do we need to list the columns in all cases? Maybe we're
1132  * replicating all columns?
1133  */
1134  for (int i = 0; i < lrel.natts; i++)
1135  {
1136  if (i > 0)
1137  appendStringInfoString(&cmd, ", ");
1138 
1140  }
1141 
1142  appendStringInfoString(&cmd, ") TO STDOUT");
1143  }
1144  else
1145  {
1146  /*
1147  * For non-tables and tables with row filters, we need to do COPY
1148  * (SELECT ...), but we can't just do SELECT * because we need to not
1149  * copy generated columns. For tables with any row filters, build a
1150  * SELECT query with OR'ed row filters for COPY.
1151  */
1152  appendStringInfoString(&cmd, "COPY (SELECT ");
1153  for (int i = 0; i < lrel.natts; i++)
1154  {
1156  if (i < lrel.natts - 1)
1157  appendStringInfoString(&cmd, ", ");
1158  }
1159 
1160  appendStringInfoString(&cmd, " FROM ");
1161 
1162  /*
1163  * For regular tables, make sure we don't copy data from a child that
1164  * inherits the named table as those will be copied separately.
1165  */
1166  if (lrel.relkind == RELKIND_RELATION)
1167  appendStringInfoString(&cmd, "ONLY ");
1168 
1170  /* list of OR'ed filters */
1171  if (qual != NIL)
1172  {
1173  ListCell *lc;
1174  char *q = strVal(linitial(qual));
1175 
1176  appendStringInfo(&cmd, " WHERE %s", q);
1177  for_each_from(lc, qual, 1)
1178  {
1179  q = strVal(lfirst(lc));
1180  appendStringInfo(&cmd, " OR %s", q);
1181  }
1182  list_free_deep(qual);
1183  }
1184 
1185  appendStringInfoString(&cmd, ") TO STDOUT");
1186  }
1187 
1188  /*
1189  * Prior to v16, initial table synchronization will use text format even
1190  * if the binary option is enabled for a subscription.
1191  */
1194  {
1195  appendStringInfoString(&cmd, " WITH (FORMAT binary)");
1196  options = list_make1(makeDefElem("format",
1197  (Node *) makeString("binary"), -1));
1198  }
1199 
1200  res = walrcv_exec(LogRepWorkerWalRcvConn, cmd.data, 0, NULL);
1201  pfree(cmd.data);
1202  if (res->status != WALRCV_OK_COPY_OUT)
1203  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)));
1208 
1209  copybuf = makeStringInfo();
1210 
1211  pstate = make_parsestate(NULL);
1212  (void) addRangeTableEntryForRelation(pstate, rel, AccessShareLock,
1213  NULL, false, false);
1214 
1215  attnamelist = make_copy_attnamelist(relmapentry);
1216  cstate = BeginCopyFrom(pstate, rel, NULL, NULL, false, copy_read_data, attnamelist, options);
1217 
1218  /* Do the copy */
1219  (void) CopyFrom(cstate);
1220 
1221  logicalrep_rel_close(relmapentry, NoLock);
1222 }
1223 
1224 /*
1225  * Determine the tablesync slot name.
1226  *
1227  * The name must not exceed NAMEDATALEN - 1 because of remote node constraints
1228  * on slot name length. We append system_identifier to avoid slot_name
1229  * collision with subscriptions in other clusters. With the current scheme
1230  * pg_%u_sync_%u_UINT64_FORMAT (3 + 10 + 6 + 10 + 20 + '\0'), the maximum
1231  * length of slot_name will be 50.
1232  *
1233  * The returned slot name is stored in the supplied buffer (syncslotname) with
1234  * the given size.
1235  *
1236  * Note: We don't use the subscription slot name as part of tablesync slot name
1237  * because we are responsible for cleaning up these slots and it could become
1238  * impossible to recalculate what name to cleanup if the subscription slot name
1239  * had changed.
1240  */
1241 void
1243  char *syncslotname, Size szslot)
1244 {
1245  snprintf(syncslotname, szslot, "pg_%u_sync_%u_" UINT64_FORMAT, suboid,
1246  relid, GetSystemIdentifier());
1247 }
1248 
1249 /*
1250  * Start syncing the table in the sync worker.
1251  *
1252  * If nothing needs to be done to sync the table, we exit the worker without
1253  * any further action.
1254  *
1255  * The returned slot name is palloc'ed in current memory context.
1256  */
1257 static char *
1259 {
1260  char *slotname;
1261  char *err;
1262  char relstate;
1263  XLogRecPtr relstate_lsn;
1264  Relation rel;
1265  AclResult aclresult;
1267  char originname[NAMEDATALEN];
1268  RepOriginId originid;
1269  UserContext ucxt;
1270  bool must_use_password;
1271  bool run_as_owner;
1272 
1273  /* Check the state of the table synchronization. */
1277  &relstate_lsn);
1278 
1279  /* Is the use of a password mandatory? */
1280  must_use_password = MySubscription->passwordrequired &&
1282 
1283  /* Note that the superuser_arg call can access the DB */
1285 
1287  MyLogicalRepWorker->relstate = relstate;
1288  MyLogicalRepWorker->relstate_lsn = relstate_lsn;
1290 
1291  /*
1292  * If synchronization is already done or no longer necessary, exit now
1293  * that we've updated shared memory state.
1294  */
1295  switch (relstate)
1296  {
1297  case SUBREL_STATE_SYNCDONE:
1298  case SUBREL_STATE_READY:
1299  case SUBREL_STATE_UNKNOWN:
1300  finish_sync_worker(); /* doesn't return */
1301  }
1302 
1303  /* Calculate the name of the tablesync slot. */
1304  slotname = (char *) palloc(NAMEDATALEN);
1307  slotname,
1308  NAMEDATALEN);
1309 
1310  /*
1311  * Here we use the slot name instead of the subscription name as the
1312  * application_name, so that it is different from the leader apply worker,
1313  * so that synchronous replication can distinguish them.
1314  */
1317  must_use_password,
1318  slotname, &err);
1319  if (LogRepWorkerWalRcvConn == NULL)
1320  ereport(ERROR,
1321  (errcode(ERRCODE_CONNECTION_FAILURE),
1322  errmsg("could not connect to the publisher: %s", err)));
1323 
1324  Assert(MyLogicalRepWorker->relstate == SUBREL_STATE_INIT ||
1325  MyLogicalRepWorker->relstate == SUBREL_STATE_DATASYNC ||
1326  MyLogicalRepWorker->relstate == SUBREL_STATE_FINISHEDCOPY);
1327 
1328  /* Assign the origin tracking record name. */
1331  originname,
1332  sizeof(originname));
1333 
1334  if (MyLogicalRepWorker->relstate == SUBREL_STATE_DATASYNC)
1335  {
1336  /*
1337  * We have previously errored out before finishing the copy so the
1338  * replication slot might exist. We want to remove the slot if it
1339  * already exists and proceed.
1340  *
1341  * XXX We could also instead try to drop the slot, last time we failed
1342  * but for that, we might need to clean up the copy state as it might
1343  * be in the middle of fetching the rows. Also, if there is a network
1344  * breakdown then it wouldn't have succeeded so trying it next time
1345  * seems like a better bet.
1346  */
1348  }
1349  else if (MyLogicalRepWorker->relstate == SUBREL_STATE_FINISHEDCOPY)
1350  {
1351  /*
1352  * The COPY phase was previously done, but tablesync then crashed
1353  * before it was able to finish normally.
1354  */
1356 
1357  /*
1358  * The origin tracking name must already exist. It was created first
1359  * time this tablesync was launched.
1360  */
1361  originid = replorigin_by_name(originname, false);
1362  replorigin_session_setup(originid, 0);
1363  replorigin_session_origin = originid;
1364  *origin_startpos = replorigin_session_get_progress(false);
1365 
1367 
1368  goto copy_table_done;
1369  }
1370 
1372  MyLogicalRepWorker->relstate = SUBREL_STATE_DATASYNC;
1375 
1376  /* Update the state and make it visible to others. */
1383  pgstat_report_stat(true);
1384 
1386 
1387  /*
1388  * Use a standard write lock here. It might be better to disallow access
1389  * to the table while it's being synchronized. But we don't want to block
1390  * the main apply process from working and it has to open the relation in
1391  * RowExclusiveLock when remapping remote relation id to local one.
1392  */
1394 
1395  /*
1396  * Start a transaction in the remote node in REPEATABLE READ mode. This
1397  * ensures that both the replication slot we create (see below) and the
1398  * COPY are consistent with each other.
1399  */
1401  "BEGIN READ ONLY ISOLATION LEVEL REPEATABLE READ",
1402  0, NULL);
1403  if (res->status != WALRCV_OK_COMMAND)
1404  ereport(ERROR,
1405  (errcode(ERRCODE_CONNECTION_FAILURE),
1406  errmsg("table copy could not start transaction on publisher: %s",
1407  res->err)));
1409 
1410  /*
1411  * Create a new permanent logical decoding slot. This slot will be used
1412  * for the catchup phase after COPY is done, so tell it to use the
1413  * snapshot to make the final data consistent.
1414  */
1416  slotname, false /* permanent */ , false /* two_phase */ ,
1417  CRS_USE_SNAPSHOT, origin_startpos);
1418 
1419  /*
1420  * Setup replication origin tracking. The purpose of doing this before the
1421  * copy is to avoid doing the copy again due to any error in setting up
1422  * origin tracking.
1423  */
1424  originid = replorigin_by_name(originname, true);
1425  if (!OidIsValid(originid))
1426  {
1427  /*
1428  * Origin tracking does not exist, so create it now.
1429  *
1430  * Then advance to the LSN got from walrcv_create_slot. This is WAL
1431  * logged for the purpose of recovery. Locks are to prevent the
1432  * replication origin from vanishing while advancing.
1433  */
1434  originid = replorigin_create(originname);
1435 
1436  LockRelationOid(ReplicationOriginRelationId, RowExclusiveLock);
1437  replorigin_advance(originid, *origin_startpos, InvalidXLogRecPtr,
1438  true /* go backward */ , true /* WAL log */ );
1439  UnlockRelationOid(ReplicationOriginRelationId, RowExclusiveLock);
1440 
1441  replorigin_session_setup(originid, 0);
1442  replorigin_session_origin = originid;
1443  }
1444  else
1445  {
1446  ereport(ERROR,
1448  errmsg("replication origin \"%s\" already exists",
1449  originname)));
1450  }
1451 
1452  /*
1453  * Make sure that the copy command runs as the table owner, unless the
1454  * user has opted out of that behaviour.
1455  */
1456  run_as_owner = MySubscription->runasowner;
1457  if (!run_as_owner)
1458  SwitchToUntrustedUser(rel->rd_rel->relowner, &ucxt);
1459 
1460  /*
1461  * Check that our table sync worker has permission to insert into the
1462  * target table.
1463  */
1464  aclresult = pg_class_aclcheck(RelationGetRelid(rel), GetUserId(),
1465  ACL_INSERT);
1466  if (aclresult != ACLCHECK_OK)
1467  aclcheck_error(aclresult,
1468  get_relkind_objtype(rel->rd_rel->relkind),
1470 
1471  /*
1472  * COPY FROM does not honor RLS policies. That is not a problem for
1473  * subscriptions owned by roles with BYPASSRLS privilege (or superuser,
1474  * who has it implicitly), but other roles should not be able to
1475  * circumvent RLS. Disallow logical replication into RLS enabled
1476  * relations for such roles.
1477  */
1479  ereport(ERROR,
1480  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1481  errmsg("user \"%s\" cannot replicate into relation with row-level security enabled: \"%s\"",
1482  GetUserNameFromId(GetUserId(), true),
1483  RelationGetRelationName(rel))));
1484 
1485  /* Now do the initial data copy */
1487  copy_table(rel);
1489 
1490  res = walrcv_exec(LogRepWorkerWalRcvConn, "COMMIT", 0, NULL);
1491  if (res->status != WALRCV_OK_COMMAND)
1492  ereport(ERROR,
1493  (errcode(ERRCODE_CONNECTION_FAILURE),
1494  errmsg("table copy could not finish transaction on publisher: %s",
1495  res->err)));
1497 
1498  if (!run_as_owner)
1499  RestoreUserContext(&ucxt);
1500 
1501  table_close(rel, NoLock);
1502 
1503  /* Make the copy visible. */
1505 
1506  /*
1507  * Update the persisted state to indicate the COPY phase is done; make it
1508  * visible to others.
1509  */
1512  SUBREL_STATE_FINISHEDCOPY,
1514 
1516 
1517 copy_table_done:
1518 
1519  elog(DEBUG1,
1520  "LogicalRepSyncTableStart: '%s' origin_startpos lsn %X/%X",
1521  originname, LSN_FORMAT_ARGS(*origin_startpos));
1522 
1523  /*
1524  * We are done with the initial data synchronization, update the state.
1525  */
1527  MyLogicalRepWorker->relstate = SUBREL_STATE_SYNCWAIT;
1528  MyLogicalRepWorker->relstate_lsn = *origin_startpos;
1530 
1531  /*
1532  * Finally, wait until the leader apply worker tells us to catch up and
1533  * then return to let LogicalRepApplyLoop do it.
1534  */
1535  wait_for_worker_state_change(SUBREL_STATE_CATCHUP);
1536  return slotname;
1537 }
1538 
1539 /*
1540  * Common code to fetch the up-to-date sync state info into the static lists.
1541  *
1542  * Returns true if subscription has 1 or more tables, else false.
1543  *
1544  * Note: If this function started the transaction (indicated by the parameter)
1545  * then it is the caller's responsibility to commit it.
1546  */
1547 static bool
1548 FetchTableStates(bool *started_tx)
1549 {
1550  static bool has_subrels = false;
1551 
1552  *started_tx = false;
1553 
1554  if (!table_states_valid)
1555  {
1556  MemoryContext oldctx;
1557  List *rstates;
1558  ListCell *lc;
1559  SubscriptionRelState *rstate;
1560 
1561  /* Clean the old lists. */
1564 
1565  if (!IsTransactionState())
1566  {
1568  *started_tx = true;
1569  }
1570 
1571  /* Fetch all non-ready tables. */
1572  rstates = GetSubscriptionRelations(MySubscription->oid, true);
1573 
1574  /* Allocate the tracking info in a permanent memory context. */
1576  foreach(lc, rstates)
1577  {
1578  rstate = palloc(sizeof(SubscriptionRelState));
1579  memcpy(rstate, lfirst(lc), sizeof(SubscriptionRelState));
1581  }
1582  MemoryContextSwitchTo(oldctx);
1583 
1584  /*
1585  * Does the subscription have tables?
1586  *
1587  * If there were not-READY relations found then we know it does. But
1588  * if table_states_not_ready was empty we still need to check again to
1589  * see if there are 0 tables.
1590  */
1591  has_subrels = (table_states_not_ready != NIL) ||
1593 
1594  table_states_valid = true;
1595  }
1596 
1597  return has_subrels;
1598 }
1599 
1600 /*
1601  * Execute the initial sync with error handling. Disable the subscription,
1602  * if it's required.
1603  *
1604  * Allocate the slot name in long-lived context on return. Note that we don't
1605  * handle FATAL errors which are probably because of system resource error and
1606  * are not repeatable.
1607  */
1608 static void
1609 start_table_sync(XLogRecPtr *origin_startpos, char **slotname)
1610 {
1611  char *sync_slotname = NULL;
1612 
1614 
1615  PG_TRY();
1616  {
1617  /* Call initial sync. */
1618  sync_slotname = LogicalRepSyncTableStart(origin_startpos);
1619  }
1620  PG_CATCH();
1621  {
1624  else
1625  {
1626  /*
1627  * Report the worker failed during table synchronization. Abort
1628  * the current transaction so that the stats message is sent in an
1629  * idle state.
1630  */
1633 
1634  PG_RE_THROW();
1635  }
1636  }
1637  PG_END_TRY();
1638 
1639  /* allocate slot name in long-lived context */
1640  *slotname = MemoryContextStrdup(ApplyContext, sync_slotname);
1641  pfree(sync_slotname);
1642 }
1643 
1644 /*
1645  * Runs the tablesync worker.
1646  *
1647  * It starts syncing tables. After a successful sync, sets streaming options
1648  * and starts streaming to catchup with apply worker.
1649  */
1650 static void
1652 {
1653  char originname[NAMEDATALEN];
1654  XLogRecPtr origin_startpos = InvalidXLogRecPtr;
1655  char *slotname = NULL;
1657 
1658  start_table_sync(&origin_startpos, &slotname);
1659 
1662  originname,
1663  sizeof(originname));
1664 
1665  set_apply_error_context_origin(originname);
1666 
1667  set_stream_options(&options, slotname, &origin_startpos);
1668 
1670 
1671  /* Apply the changes till we catchup with the apply worker. */
1672  start_apply(origin_startpos);
1673 }
1674 
1675 /* Logical Replication Tablesync worker entry point */
1676 void
1678 {
1679  int worker_slot = DatumGetInt32(main_arg);
1680 
1681  SetupApplyOrSyncWorker(worker_slot);
1682 
1684 
1685  finish_sync_worker();
1686 }
1687 
1688 /*
1689  * If the subscription has no tables then return false.
1690  *
1691  * Otherwise, are all tablesyncs READY?
1692  *
1693  * Note: This function is not suitable to be called from outside of apply or
1694  * tablesync workers because MySubscription needs to be already initialized.
1695  */
1696 bool
1698 {
1699  bool started_tx = false;
1700  bool has_subrels = false;
1701 
1702  /* We need up-to-date sync state info for subscription tables here. */
1703  has_subrels = FetchTableStates(&started_tx);
1704 
1705  if (started_tx)
1706  {
1708  pgstat_report_stat(true);
1709  }
1710 
1711  /*
1712  * Return false when there are no tables in subscription or not all tables
1713  * are in ready state; true otherwise.
1714  */
1715  return has_subrels && (table_states_not_ready == NIL);
1716 }
1717 
1718 /*
1719  * Update the two_phase state of the specified subscription in pg_subscription.
1720  */
1721 void
1722 UpdateTwoPhaseState(Oid suboid, char new_state)
1723 {
1724  Relation rel;
1725  HeapTuple tup;
1726  bool nulls[Natts_pg_subscription];
1727  bool replaces[Natts_pg_subscription];
1728  Datum values[Natts_pg_subscription];
1729 
1731  new_state == LOGICALREP_TWOPHASE_STATE_PENDING ||
1732  new_state == LOGICALREP_TWOPHASE_STATE_ENABLED);
1733 
1734  rel = table_open(SubscriptionRelationId, RowExclusiveLock);
1736  if (!HeapTupleIsValid(tup))
1737  elog(ERROR,
1738  "cache lookup failed for subscription oid %u",
1739  suboid);
1740 
1741  /* Form a new tuple. */
1742  memset(values, 0, sizeof(values));
1743  memset(nulls, false, sizeof(nulls));
1744  memset(replaces, false, sizeof(replaces));
1745 
1746  /* And update/set two_phase state */
1747  values[Anum_pg_subscription_subtwophasestate - 1] = CharGetDatum(new_state);
1748  replaces[Anum_pg_subscription_subtwophasestate - 1] = true;
1749 
1750  tup = heap_modify_tuple(tup, RelationGetDescr(rel),
1751  values, nulls, replaces);
1752  CatalogTupleUpdate(rel, &tup->t_self, tup);
1753 
1754  heap_freetuple(tup);
1756 }
AclResult
Definition: acl.h:181
@ ACLCHECK_OK
Definition: acl.h:182
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition: aclchk.c:2669
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition: aclchk.c:3908
#define ARR_DATA_PTR(a)
Definition: array.h:315
#define DatumGetArrayTypeP(X)
Definition: array.h:254
#define ARR_DIMS(a)
Definition: array.h:287
int16 AttrNumber
Definition: attnum.h:21
void set_stream_options(WalRcvStreamOptions *options, char *slotname, XLogRecPtr *origin_startpos)
Definition: worker.c:4343
void start_apply(XLogRecPtr origin_startpos)
Definition: worker.c:4430
void DisableSubscriptionAndExit(void)
Definition: worker.c:4705
void ReplicationOriginNameForLogicalRep(Oid suboid, Oid relid, char *originname, Size szoriginname)
Definition: worker.c:446
void set_apply_error_context_origin(char *originname)
Definition: worker.c:5035
MemoryContext ApplyContext
Definition: worker.c:309
void SetupApplyOrSyncWorker(int worker_slot)
Definition: worker.c:4644
WalReceiverConn * LogRepWorkerWalRcvConn
Definition: worker.c:314
Subscription * MySubscription
Definition: worker.c:316
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1719
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1583
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1547
bool bms_is_member(int x, const Bitmapset *a)
Definition: bitmapset.c:460
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:753
static Datum values[MAXATTR]
Definition: bootstrap.c:156
#define TextDatumGetCString(d)
Definition: builtins.h:95
unsigned int uint32
Definition: c.h:495
signed short int16
Definition: c.h:482
#define Max(x, y)
Definition: c.h:987
#define UINT64_FORMAT
Definition: c.h:538
#define lengthof(array)
Definition: c.h:777
#define OidIsValid(objectId)
Definition: c.h:764
size_t Size
Definition: c.h:594
CopyFromState BeginCopyFrom(ParseState *pstate, Relation rel, Node *whereClause, const char *filename, bool is_program, copy_data_source_cb data_source_cb, List *attnamelist, List *options)
Definition: copyfrom.c:1334
uint64 CopyFrom(CopyFromState cstate)
Definition: copyfrom.c:632
int64 TimestampTz
Definition: timestamp.h:39
#define DSM_HANDLE_INVALID
Definition: dsm_impl.h:58
void hash_destroy(HTAB *hashp)
Definition: dynahash.c:863
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:953
HTAB * hash_create(const char *tabname, long nelem, const HASHCTL *info, int flags)
Definition: dynahash.c:350
int errcode(int sqlerrcode)
Definition: elog.c:858
int errmsg(const char *fmt,...)
Definition: elog.c:1069
#define LOG
Definition: elog.h:31
#define PG_RE_THROW()
Definition: elog.h:411
#define PG_TRY(...)
Definition: elog.h:370
#define PG_END_TRY(...)
Definition: elog.h:395
#define DEBUG1
Definition: elog.h:30
#define ERROR
Definition: elog.h:39
#define PG_CATCH(...)
Definition: elog.h:380
#define ereport(elevel,...)
Definition: elog.h:149
void err(int eval, const char *fmt,...)
Definition: err.c:43
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1255
const TupleTableSlotOps TTSOpsMinimalTuple
Definition: execTuples.c:85
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1239
struct Latch * MyLatch
Definition: globals.c:58
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, Datum *replValues, bool *replIsnull, bool *doReplace)
Definition: heaptuple.c:1201
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1426
@ HASH_ENTER
Definition: hsearch.h:114
#define HASH_ELEM
Definition: hsearch.h:95
#define HASH_BLOBS
Definition: hsearch.h:97
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define MaxTupleAttributeNumber
Definition: htup_details.h:34
void CatalogTupleUpdate(Relation heapRel, ItemPointer otid, HeapTuple tup)
Definition: indexing.c:313
void proc_exit(int code)
Definition: ipc.c:104
int i
Definition: isn.c:73
int WaitLatchOrSocket(Latch *latch, int wakeEvents, pgsocket sock, long timeout, uint32 wait_event_info)
Definition: latch.c:538
void ResetLatch(Latch *latch)
Definition: latch.c:697
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:490
#define WL_SOCKET_READABLE
Definition: latch.h:126
#define WL_TIMEOUT
Definition: latch.h:128
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:130
#define WL_LATCH_SET
Definition: latch.h:125
bool logicalrep_worker_launch(LogicalRepWorkerType wtype, Oid dbid, Oid subid, const char *subname, Oid userid, Oid relid, dsm_handle subworker_dsm)
Definition: launcher.c:306
LogicalRepWorker * logicalrep_worker_find(Oid subid, Oid relid, bool only_running)
Definition: launcher.c:249
void logicalrep_worker_wakeup_ptr(LogicalRepWorker *worker)
Definition: launcher.c:702
void logicalrep_worker_wakeup(Oid subid, Oid relid)
Definition: launcher.c:682
static dshash_table * last_start_times
Definition: launcher.c:95
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:61
int max_sync_workers_per_subscription
Definition: launcher.c:58
int logicalrep_sync_worker_count(Oid subid)
Definition: launcher.c:854
void ApplyLauncherForgetWorkerStartTime(Oid subid)
Definition: launcher.c:1074
Assert(fmt[strlen(fmt) - 1] !='\n')
List * lappend(List *list, void *datum)
Definition: list.c:338
void list_free_deep(List *list)
Definition: list.c:1559
void UnlockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:228
void LockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:109
#define NoLock
Definition: lockdefs.h:34
#define AccessShareLock
Definition: lockdefs.h:36
#define RowExclusiveLock
Definition: lockdefs.h:38
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3348
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1932
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1195
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1808
@ LW_SHARED
Definition: lwlock.h:117
DefElem * makeDefElem(char *name, Node *arg, int location)
Definition: makefuncs.c:549
void pfree(void *pointer)
Definition: mcxt.c:1456
void * palloc0(Size size)
Definition: mcxt.c:1257
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition: mcxt.c:1631
MemoryContext CacheMemoryContext
Definition: mcxt.c:144
void * palloc(Size size)
Definition: mcxt.c:1226
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:121
char * GetUserNameFromId(Oid roleid, bool noerr)
Definition: miscinit.c:966
Oid GetUserId(void)
Definition: miscinit.c:509
ObjectType get_relkind_objtype(char relkind)
TimestampTz replorigin_session_origin_timestamp
Definition: origin.c:158
RepOriginId replorigin_by_name(const char *roname, bool missing_ok)
Definition: origin.c:221
RepOriginId replorigin_create(const char *roname)
Definition: origin.c:252
void replorigin_session_reset(void)
Definition: origin.c:1187
void replorigin_drop_by_name(const char *name, bool missing_ok, bool nowait)
Definition: origin.c:411
RepOriginId replorigin_session_origin
Definition: origin.c:156
void replorigin_advance(RepOriginId node, XLogRecPtr remote_commit, XLogRecPtr local_commit, bool go_backward, bool wal_log)
Definition: origin.c:888
void replorigin_session_setup(RepOriginId node, int acquired_by)
Definition: origin.c:1095
XLogRecPtr replorigin_session_get_progress(bool flush)
Definition: origin.c:1234
XLogRecPtr replorigin_session_origin_lsn
Definition: origin.c:157
#define InvalidRepOriginId
Definition: origin.h:33
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:138
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
ParseNamespaceItem * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, int lockmode, Alias *alias, bool inh, bool inFromCl)
#define ACL_INSERT
Definition: parsenodes.h:83
int16 attnum
Definition: pg_attribute.h:74
void * arg
NameData relname
Definition: pg_class.h:38
#define NAMEDATALEN
const void size_t len
#define lfirst(lc)
Definition: pg_list.h:172
#define NIL
Definition: pg_list.h:68
#define list_make1(x1)
Definition: pg_list.h:212
#define for_each_from(cell, lst, N)
Definition: pg_list.h:414
#define linitial(l)
Definition: pg_list.h:178
#define foreach_current_index(cell)
Definition: pg_list.h:403
static char ** options
List * GetSubscriptionRelations(Oid subid, bool not_ready)
char GetSubscriptionRelState(Oid subid, Oid relid, XLogRecPtr *sublsn)
void UpdateSubscriptionRelState(Oid subid, Oid relid, char state, XLogRecPtr sublsn)
bool HasSubscriptionRelations(Oid subid)
#define LOGICALREP_TWOPHASE_STATE_DISABLED
#define LOGICALREP_TWOPHASE_STATE_PENDING
#define LOGICALREP_TWOPHASE_STATE_ENABLED
static char * buf
Definition: pg_test_fsync.c:67
long pgstat_report_stat(bool force)
Definition: pgstat.c:582
void pgstat_report_subscription_error(Oid subid, bool is_apply_error)
int pgsocket
Definition: port.h:29
#define snprintf
Definition: port.h:238
#define PGINVALID_SOCKET
Definition: port.h:31
static bool DatumGetBool(Datum X)
Definition: postgres.h:90
uintptr_t Datum
Definition: postgres.h:64
static Oid DatumGetObjectId(Datum X)
Definition: postgres.h:242
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:252
static char DatumGetChar(Datum X)
Definition: postgres.h:112
static int16 DatumGetInt16(Datum X)
Definition: postgres.h:162
static int32 DatumGetInt32(Datum X)
Definition: postgres.h:202
static Datum CharGetDatum(char X)
Definition: postgres.h:122
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
static int fd(const char *x, int i)
Definition: preproc-init.c:105
char * quote_literal_cstr(const char *rawstr)
Definition: quote.c:103
#define RelationGetRelid(relation)
Definition: rel.h:504
#define RelationGetDescr(relation)
Definition: rel.h:530
#define RelationGetRelationName(relation)
Definition: rel.h:538
#define RelationGetNamespace(relation)
Definition: rel.h:545
int check_enable_rls(Oid relid, Oid checkAsUser, bool noError)
Definition: rls.c:52
@ RLS_ENABLED
Definition: rls.h:45
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:11965
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:12049
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:197
void PushActiveSnapshot(Snapshot snapshot)
Definition: snapmgr.c:629
void PopActiveSnapshot(void)
Definition: snapmgr.c:724
void InvalidateCatalogSnapshot(void)
Definition: snapmgr.c:403
#define SpinLockRelease(lock)
Definition: spin.h:64
#define SpinLockAcquire(lock)
Definition: spin.h:62
void logicalrep_relmap_update(LogicalRepRelation *remoterel)
Definition: relation.c:165
LogicalRepRelMapEntry * logicalrep_rel_open(LogicalRepRelId remoteid, LOCKMODE lockmode)
Definition: relation.c:328
void logicalrep_rel_close(LogicalRepRelMapEntry *rel, LOCKMODE lockmode)
Definition: relation.c:474
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:32
StringInfo makeStringInfo(void)
Definition: stringinfo.c:41
void resetStringInfo(StringInfo str)
Definition: stringinfo.c:75
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
Size keysize
Definition: hsearch.h:75
Size entrysize
Definition: hsearch.h:76
Definition: dynahash.c:220
ItemPointerData t_self
Definition: htup.h:65
Definition: pg_list.h:54
LogicalRepRelation remoterel
LogicalRepRelId remoteid
Definition: logicalproto.h:107
Bitmapset * attkeys
Definition: logicalproto.h:115
XLogRecPtr relstate_lsn
LogicalRepWorkerType type
Definition: nodes.h:129
Form_pg_class rd_rel
Definition: rel.h:111
Tuplestorestate * tuplestore
Definition: walreceiver.h:223
TupleDesc tupledesc
Definition: walreceiver.h:224
WalRcvExecStatus status
Definition: walreceiver.h:220
Definition: regguts.h:323
void ReplicationSlotDropAtPubNode(WalReceiverConn *wrconn, char *slotname, bool missing_ok)
bool superuser_arg(Oid roleid)
Definition: superuser.c:56
#define SearchSysCacheCopy1(cacheId, key1)
Definition: syscache.h:182
@ SUBSCRIPTIONOID
Definition: syscache.h:99
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:40
static List * table_states_not_ready
Definition: tablesync.c:127
bool AllTablesyncsReady(void)
Definition: tablesync.c:1697
static bool wait_for_worker_state_change(char expected_state)
Definition: tablesync.c:225
static bool table_states_valid
Definition: tablesync.c:126
static char * LogicalRepSyncTableStart(XLogRecPtr *origin_startpos)
Definition: tablesync.c:1258
void invalidate_syncing_table_states(Datum arg, int cacheid, uint32 hashvalue)
Definition: tablesync.c:274
static void pg_attribute_noreturn() finish_sync_worker(void)
Definition: tablesync.c:136
static void process_syncing_tables_for_apply(XLogRecPtr current_lsn)
Definition: tablesync.c:411
void TablesyncWorkerMain(Datum main_arg)
Definition: tablesync.c:1677
static void process_syncing_tables_for_sync(XLogRecPtr current_lsn)
Definition: tablesync.c:288
void ReplicationSlotNameForTablesync(Oid suboid, Oid relid, char *syncslotname, Size szslot)
Definition: tablesync.c:1242
static void run_tablesync_worker()
Definition: tablesync.c:1651
static int copy_read_data(void *outbuf, int minread, int maxread)
Definition: tablesync.c:701
void process_syncing_tables(XLogRecPtr current_lsn)
Definition: tablesync.c:650
static void copy_table(Relation rel)
Definition: tablesync.c:1098
static bool wait_for_relation_state_change(Oid relid, char expected_state)
Definition: tablesync.c:177
static void start_table_sync(XLogRecPtr *origin_startpos, char **slotname)
Definition: tablesync.c:1609
static StringInfo copybuf
Definition: tablesync.c:130
static bool FetchTableStates(bool *started_tx)
Definition: tablesync.c:1548
static void fetch_remote_table_info(char *nspname, char *relname, LogicalRepRelation *lrel, List **qual)
Definition: tablesync.c:777
static List * make_copy_attnamelist(LogicalRepRelMapEntry *rel)
Definition: tablesync.c:681
void UpdateTwoPhaseState(Oid suboid, char new_state)
Definition: tablesync.c:1722
bool tuplestore_gettupleslot(Tuplestorestate *state, bool forward, bool copy, TupleTableSlot *slot)
Definition: tuplestore.c:1078
int64 tuplestore_tuple_count(Tuplestorestate *state)
Definition: tuplestore.c:546
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:432
static Datum slot_getattr(TupleTableSlot *slot, int attnum, bool *isnull)
Definition: tuptable.h:388
void SwitchToUntrustedUser(Oid userid, UserContext *context)
Definition: usercontext.c:33
void RestoreUserContext(UserContext *context)
Definition: usercontext.c:87
String * makeString(char *str)
Definition: value.c:63
#define strVal(v)
Definition: value.h:82
#define walrcv_create_slot(conn, slotname, temporary, two_phase, snapshot_action, lsn)
Definition: walreceiver.h:432
#define walrcv_startstreaming(conn, options)
Definition: walreceiver.h:424
@ WALRCV_OK_COMMAND
Definition: walreceiver.h:205
@ WALRCV_OK_TUPLES
Definition: walreceiver.h:207
@ WALRCV_OK_COPY_OUT
Definition: walreceiver.h:209
static void walrcv_clear_result(WalRcvExecResult *walres)
Definition: walreceiver.h:442
#define walrcv_server_version(conn)
Definition: walreceiver.h:420
#define walrcv_endstreaming(conn, next_tli)
Definition: walreceiver.h:426
#define walrcv_connect(conninfo, logical, must_use_password, appname, err)
Definition: walreceiver.h:410
#define walrcv_exec(conn, exec, nRetTypes, retTypes)
Definition: walreceiver.h:436
#define walrcv_receive(conn, buffer, wait_fd)
Definition: walreceiver.h:428
@ CRS_USE_SNAPSHOT
Definition: walsender.h:24
@ WORKERTYPE_TABLESYNC
@ WORKERTYPE_UNKNOWN
@ WORKERTYPE_PARALLEL_APPLY
@ WORKERTYPE_APPLY
static bool am_tablesync_worker(void)
bool IsTransactionState(void)
Definition: xact.c:378
void CommandCounterIncrement(void)
Definition: xact.c:1078
void StartTransactionCommand(void)
Definition: xact.c:2937
void CommitTransactionCommand(void)
Definition: xact.c:3034
void AbortOutOfAnyTransaction(void)
Definition: xact.c:4712
uint64 GetSystemIdentifier(void)
Definition: xlog.c:4203
XLogRecPtr GetXLogWriteRecPtr(void)
Definition: xlog.c:8939
int wal_retrieve_retry_interval
Definition: xlog.c:137
void XLogFlush(XLogRecPtr record)
Definition: xlog.c:2535
#define LSN_FORMAT_ARGS(lsn)
Definition: xlogdefs.h:43
uint16 RepOriginId
Definition: xlogdefs.h:65
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
uint32 TimeLineID
Definition: xlogdefs.h:59