PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
worker.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  * worker.c
3  * PostgreSQL logical replication worker (apply)
4  *
5  * Copyright (c) 2016-2017, PostgreSQL Global Development Group
6  *
7  * IDENTIFICATION
8  * src/backend/replication/logical/worker.c
9  *
10  * NOTES
11  * This file contains the worker which applies logical changes as they come
12  * from remote logical replication stream.
13  *
14  * The main worker (apply) is started by logical replication worker
15  * launcher for every enabled subscription in a database. It uses
16  * walsender protocol to communicate with publisher.
17  *
18  * This module includes server facing code and shares libpqwalreceiver
19  * module with walreceiver for providing the libpq specific functionality.
20  *
21  *-------------------------------------------------------------------------
22  */
23 
24 #include "postgres.h"
25 
26 #include "miscadmin.h"
27 #include "pgstat.h"
28 #include "funcapi.h"
29 
30 #include "access/xact.h"
31 #include "access/xlog_internal.h"
32 
33 #include "catalog/namespace.h"
36 
37 #include "commands/trigger.h"
38 
39 #include "executor/executor.h"
41 
42 #include "libpq/pqformat.h"
43 #include "libpq/pqsignal.h"
44 
45 #include "mb/pg_wchar.h"
46 
47 #include "nodes/makefuncs.h"
48 
49 #include "optimizer/planner.h"
50 
51 #include "parser/parse_relation.h"
52 
53 #include "postmaster/bgworker.h"
54 #include "postmaster/postmaster.h"
55 
56 #include "replication/decode.h"
57 #include "replication/logical.h"
62 #include "replication/origin.h"
63 #include "replication/snapbuild.h"
66 
67 #include "rewrite/rewriteHandler.h"
68 
69 #include "storage/bufmgr.h"
70 #include "storage/ipc.h"
71 #include "storage/lmgr.h"
72 #include "storage/proc.h"
73 #include "storage/procarray.h"
74 
75 #include "utils/builtins.h"
76 #include "utils/catcache.h"
77 #include "utils/datum.h"
78 #include "utils/fmgroids.h"
79 #include "utils/guc.h"
80 #include "utils/inval.h"
81 #include "utils/lsyscache.h"
82 #include "utils/memutils.h"
83 #include "utils/timeout.h"
84 #include "utils/tqual.h"
85 #include "utils/syscache.h"
86 
87 #define NAPTIME_PER_CYCLE 1000 /* max sleep time between cycles (1s) */
88 
89 typedef struct FlushPosition
90 {
95 
97 
98 typedef struct SlotErrCallbackArg
99 {
101  int attnum;
103 
106 
108 
110 bool MySubscriptionValid = false;
111 
114 
115 static void send_feedback(XLogRecPtr recvpos, bool force, bool requestReply);
116 
117 static void store_flush_position(XLogRecPtr remote_lsn);
118 
119 static void reread_subscription(void);
120 
121 /*
122  * Should this worker apply changes for given relation.
123  *
124  * This is mainly needed for initial relation data sync as that runs in
125  * separate worker process running in parallel and we need some way to skip
126  * changes coming to the main apply worker during the sync of a table.
127  *
128  * Note we need to do smaller or equals comparison for SYNCDONE state because
129  * it might hold position of end of intitial slot consistent point WAL
130  * record + 1 (ie start of next record) and next record can be COMMIT of
131  * transaction we are now processing (which is what we set remote_final_lsn
132  * to in apply_handle_begin).
133  */
134 static bool
136 {
137  if (am_tablesync_worker())
138  return MyLogicalRepWorker->relid == rel->localreloid;
139  else
140  return (rel->state == SUBREL_STATE_READY ||
141  (rel->state == SUBREL_STATE_SYNCDONE &&
142  rel->statelsn <= remote_final_lsn));
143 }
144 
145 /*
146  * Make sure that we started local transaction.
147  *
148  * Also switches to ApplyContext as necessary.
149  */
150 static bool
152 {
153  if (IsTransactionState())
154  {
155  if (CurrentMemoryContext != ApplyContext)
156  MemoryContextSwitchTo(ApplyContext);
157  return false;
158  }
159 
161 
162  if (!MySubscriptionValid)
164 
165  MemoryContextSwitchTo(ApplyContext);
166  return true;
167 }
168 
169 
170 /*
171  * Executor state preparation for evaluation of constraint expressions,
172  * indexes and triggers.
173  *
174  * This is based on similar code in copy.c
175  */
176 static EState *
178 {
179  EState *estate;
180  ResultRelInfo *resultRelInfo;
181  RangeTblEntry *rte;
182 
183  estate = CreateExecutorState();
184 
185  rte = makeNode(RangeTblEntry);
186  rte->rtekind = RTE_RELATION;
187  rte->relid = RelationGetRelid(rel->localrel);
188  rte->relkind = rel->localrel->rd_rel->relkind;
189  estate->es_range_table = list_make1(rte);
190 
191  resultRelInfo = makeNode(ResultRelInfo);
192  InitResultRelInfo(resultRelInfo, rel->localrel, 1, NULL, 0);
193 
194  estate->es_result_relations = resultRelInfo;
195  estate->es_num_result_relations = 1;
196  estate->es_result_relation_info = resultRelInfo;
197 
198  /* Triggers might need a slot */
199  if (resultRelInfo->ri_TrigDesc)
200  estate->es_trig_tuple_slot = ExecInitExtraTupleSlot(estate);
201 
202  /* Prepare to catch AFTER triggers. */
204 
205  return estate;
206 }
207 
208 /*
209  * Executes default values for columns for which we can't map to remote
210  * relation columns.
211  *
212  * This allows us to support tables which have more columns on the downstream
213  * than on the upstream.
214  */
215 static void
217  TupleTableSlot *slot)
218 {
219  TupleDesc desc = RelationGetDescr(rel->localrel);
220  int num_phys_attrs = desc->natts;
221  int i;
222  int attnum,
223  num_defaults = 0;
224  int *defmap;
225  ExprState **defexprs;
226  ExprContext *econtext;
227 
228  econtext = GetPerTupleExprContext(estate);
229 
230  /* We got all the data via replication, no need to evaluate anything. */
231  if (num_phys_attrs == rel->remoterel.natts)
232  return;
233 
234  defmap = (int *) palloc(num_phys_attrs * sizeof(int));
235  defexprs = (ExprState **) palloc(num_phys_attrs * sizeof(ExprState *));
236 
237  for (attnum = 0; attnum < num_phys_attrs; attnum++)
238  {
239  Expr *defexpr;
240 
241  if (desc->attrs[attnum]->attisdropped)
242  continue;
243 
244  if (rel->attrmap[attnum] >= 0)
245  continue;
246 
247  defexpr = (Expr *) build_column_default(rel->localrel, attnum + 1);
248 
249  if (defexpr != NULL)
250  {
251  /* Run the expression through planner */
252  defexpr = expression_planner(defexpr);
253 
254  /* Initialize executable expression in copycontext */
255  defexprs[num_defaults] = ExecInitExpr(defexpr, NULL);
256  defmap[num_defaults] = attnum;
257  num_defaults++;
258  }
259 
260  }
261 
262  for (i = 0; i < num_defaults; i++)
263  slot->tts_values[defmap[i]] =
264  ExecEvalExpr(defexprs[i], econtext, &slot->tts_isnull[defmap[i]]);
265 }
266 
267 /*
268  * Error callback to give more context info about type conversion failure.
269  */
270 static void
272 {
273  SlotErrCallbackArg *errarg = (SlotErrCallbackArg *) arg;
274  Oid remotetypoid,
275  localtypoid;
276 
277  if (errarg->attnum < 0)
278  return;
279 
280  remotetypoid = errarg->rel->atttyps[errarg->attnum];
281  localtypoid = logicalrep_typmap_getid(remotetypoid);
282  errcontext("processing remote data for replication target relation \"%s.%s\" column \"%s\", "
283  "remote type %s, local type %s",
284  errarg->rel->nspname, errarg->rel->relname,
285  errarg->rel->attnames[errarg->attnum],
286  format_type_be(remotetypoid),
287  format_type_be(localtypoid));
288 }
289 
290 /*
291  * Store data in C string form into slot.
292  * This is similar to BuildTupleFromCStrings but TupleTableSlot fits our
293  * use better.
294  */
295 static void
297  char **values)
298 {
299  int natts = slot->tts_tupleDescriptor->natts;
300  int i;
301  SlotErrCallbackArg errarg;
302  ErrorContextCallback errcallback;
303 
304  ExecClearTuple(slot);
305 
306  /* Push callback + info on the error context stack */
307  errarg.rel = &rel->remoterel;
308  errarg.attnum = -1;
309  errcallback.callback = slot_store_error_callback;
310  errcallback.arg = (void *) &errarg;
311  errcallback.previous = error_context_stack;
312  error_context_stack = &errcallback;
313 
314  /* Call the "in" function for each non-dropped attribute */
315  for (i = 0; i < natts; i++)
316  {
318  int remoteattnum = rel->attrmap[i];
319 
320  if (!att->attisdropped && remoteattnum >= 0 &&
321  values[remoteattnum] != NULL)
322  {
323  Oid typinput;
324  Oid typioparam;
325 
326  errarg.attnum = remoteattnum;
327 
328  getTypeInputInfo(att->atttypid, &typinput, &typioparam);
329  slot->tts_values[i] = OidInputFunctionCall(typinput,
330  values[remoteattnum],
331  typioparam,
332  att->atttypmod);
333  slot->tts_isnull[i] = false;
334  }
335  else
336  {
337  /*
338  * We assign NULL to dropped attributes, NULL values, and missing
339  * values (missing values should be later filled using
340  * slot_fill_defaults).
341  */
342  slot->tts_values[i] = (Datum) 0;
343  slot->tts_isnull[i] = true;
344  }
345  }
346 
347  /* Pop the error context stack */
348  error_context_stack = errcallback.previous;
349 
350  ExecStoreVirtualTuple(slot);
351 }
352 
353 /*
354  * Modify slot with user data provided as C strigs.
355  * This is somewhat similar to heap_modify_tuple but also calls the type
356  * input function on the user data as the input is the text representation
357  * of the types.
358  */
359 static void
361  char **values, bool *replaces)
362 {
363  int natts = slot->tts_tupleDescriptor->natts;
364  int i;
365  SlotErrCallbackArg errarg;
366  ErrorContextCallback errcallback;
367 
368  slot_getallattrs(slot);
369  ExecClearTuple(slot);
370 
371  /* Push callback + info on the error context stack */
372  errarg.rel = &rel->remoterel;
373  errarg.attnum = -1;
374  errcallback.callback = slot_store_error_callback;
375  errcallback.arg = (void *) &errarg;
376  errcallback.previous = error_context_stack;
377  error_context_stack = &errcallback;
378 
379  /* Call the "in" function for each replaced attribute */
380  for (i = 0; i < natts; i++)
381  {
383  int remoteattnum = rel->attrmap[i];
384 
385  if (remoteattnum >= 0 && !replaces[remoteattnum])
386  continue;
387 
388  if (remoteattnum >= 0 && values[remoteattnum] != NULL)
389  {
390  Oid typinput;
391  Oid typioparam;
392 
393  errarg.attnum = remoteattnum;
394 
395  getTypeInputInfo(att->atttypid, &typinput, &typioparam);
396  slot->tts_values[i] = OidInputFunctionCall(typinput, values[i],
397  typioparam,
398  att->atttypmod);
399  slot->tts_isnull[i] = false;
400  }
401  else
402  {
403  slot->tts_values[i] = (Datum) 0;
404  slot->tts_isnull[i] = true;
405  }
406  }
407 
408  /* Pop the error context stack */
409  error_context_stack = errcallback.previous;
410 
411  ExecStoreVirtualTuple(slot);
412 }
413 
414 /*
415  * Handle BEGIN message.
416  */
417 static void
419 {
420  LogicalRepBeginData begin_data;
421 
422  logicalrep_read_begin(s, &begin_data);
423 
426 
427  remote_final_lsn = begin_data.final_lsn;
428 
429  in_remote_transaction = true;
430 
432 }
433 
434 /*
435  * Handle COMMIT message.
436  *
437  * TODO, support tracking of multiple origins
438  */
439 static void
441 {
442  LogicalRepCommitData commit_data;
443 
444  logicalrep_read_commit(s, &commit_data);
445 
448 
449  Assert(commit_data.commit_lsn == remote_final_lsn);
450 
451  /* The synchronization worker runs in single transaction. */
453  {
455 
456  store_flush_position(commit_data.end_lsn);
457  }
458 
459  in_remote_transaction = false;
460 
461  /* Process any tables that are being synchronized in parallel. */
462  process_syncing_tables(commit_data.end_lsn);
463 
465 }
466 
467 /*
468  * Handle ORIGIN message.
469  *
470  * TODO, support tracking of multiple origins
471  */
472 static void
474 {
475  /*
476  * ORIGIN message can only come inside remote transaction and before
477  * any actual writes.
478  */
479  if (!in_remote_transaction ||
481  ereport(ERROR,
482  (errcode(ERRCODE_PROTOCOL_VIOLATION),
483  errmsg("ORIGIN message sent out of order")));
484 }
485 
486 /*
487  * Handle RELATION message.
488  *
489  * Note we don't do validation against local schema here. The validation
490  * against local schema is postponed until first change for given relation
491  * comes as we only care about it when applying changes for it anyway and we
492  * do less locking this way.
493  */
494 static void
496 {
497  LogicalRepRelation *rel;
498 
499  rel = logicalrep_read_rel(s);
501 }
502 
503 /*
504  * Handle TYPE message.
505  *
506  * Note we don't do local mapping here, that's done when the type is
507  * actually used.
508  */
509 static void
511 {
512  LogicalRepTyp typ;
513 
514  logicalrep_read_typ(s, &typ);
516 }
517 
518 /*
519  * Get replica identity index or if it is not defined a primary key.
520  *
521  * If neither is defined, returns InvalidOid
522  */
523 static Oid
525 {
526  Oid idxoid;
527 
528  idxoid = RelationGetReplicaIndex(rel);
529 
530  if (!OidIsValid(idxoid))
531  idxoid = RelationGetPrimaryKeyIndex(rel);
532 
533  return idxoid;
534 }
535 
536 /*
537  * Handle INSERT message.
538  */
539 static void
541 {
543  LogicalRepTupleData newtup;
544  LogicalRepRelId relid;
545  EState *estate;
546  TupleTableSlot *remoteslot;
547  MemoryContext oldctx;
548 
550 
551  relid = logicalrep_read_insert(s, &newtup);
554  {
555  /*
556  * The relation can't become interesting in the middle of the
557  * transaction so it's safe to unlock it.
558  */
560  return;
561  }
562 
563  /* Initialize the executor state. */
564  estate = create_estate_for_relation(rel);
565  remoteslot = ExecInitExtraTupleSlot(estate);
567 
568  /* Process and store remote tuple in the slot */
570  slot_store_cstrings(remoteslot, rel, newtup.values);
571  slot_fill_defaults(rel, estate, remoteslot);
572  MemoryContextSwitchTo(oldctx);
573 
576 
577  /* Do the insert. */
578  ExecSimpleRelationInsert(estate, remoteslot);
579 
580  /* Cleanup. */
583 
584  /* Handle queued AFTER triggers. */
585  AfterTriggerEndQuery(estate);
586 
587  ExecResetTupleTable(estate->es_tupleTable, false);
588  FreeExecutorState(estate);
589 
591 
593 }
594 
595 /*
596  * Check if the logical replication relation is updatable and throw
597  * appropriate error if it isn't.
598  */
599 static void
601 {
602  /* Updatable, no error. */
603  if (rel->updatable)
604  return;
605 
606  /*
607  * We are in error mode so it's fine this is somewhat slow.
608  * It's better to give user correct error.
609  */
611  {
612  ereport(ERROR,
613  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
614  errmsg("publisher does not send replica identity column "
615  "expected by the logical replication target relation \"%s.%s\"",
616  rel->remoterel.nspname, rel->remoterel.relname)));
617  }
618 
619  ereport(ERROR,
620  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
621  errmsg("logical replication target relation \"%s.%s\" has "
622  "neither REPLICA IDENTITY index nor PRIMARY "
623  "KEY and published relation does not have "
624  "REPLICA IDENTITY FULL",
625  rel->remoterel.nspname, rel->remoterel.relname)));
626 }
627 
628 /*
629  * Handle UPDATE message.
630  *
631  * TODO: FDW support
632  */
633 static void
635 {
637  LogicalRepRelId relid;
638  Oid idxoid;
639  EState *estate;
640  EPQState epqstate;
641  LogicalRepTupleData oldtup;
642  LogicalRepTupleData newtup;
643  bool has_oldtup;
644  TupleTableSlot *localslot;
645  TupleTableSlot *remoteslot;
646  bool found;
647  MemoryContext oldctx;
648 
650 
651  relid = logicalrep_read_update(s, &has_oldtup, &oldtup,
652  &newtup);
655  {
656  /*
657  * The relation can't become interesting in the middle of the
658  * transaction so it's safe to unlock it.
659  */
661  return;
662  }
663 
664  /* Check if we can do the update. */
666 
667  /* Initialize the executor state. */
668  estate = create_estate_for_relation(rel);
669  remoteslot = ExecInitExtraTupleSlot(estate);
671  localslot = ExecInitExtraTupleSlot(estate);
673  EvalPlanQualInit(&epqstate, estate, NULL, NIL, -1);
674 
677 
678  /* Build the search tuple. */
680  slot_store_cstrings(remoteslot, rel,
681  has_oldtup ? oldtup.values : newtup.values);
682  MemoryContextSwitchTo(oldctx);
683 
684  /*
685  * Try to find tuple using either replica identity index, primary key
686  * or if needed, sequential scan.
687  */
688  idxoid = GetRelationIdentityOrPK(rel->localrel);
689  Assert(OidIsValid(idxoid) ||
690  (rel->remoterel.replident == REPLICA_IDENTITY_FULL && has_oldtup));
691 
692  if (OidIsValid(idxoid))
693  found = RelationFindReplTupleByIndex(rel->localrel, idxoid,
695  remoteslot, localslot);
696  else
698  remoteslot, localslot);
699 
700  ExecClearTuple(remoteslot);
701 
702  /*
703  * Tuple found.
704  *
705  * Note this will fail if there are other conflicting unique indexes.
706  */
707  if (found)
708  {
709  /* Process and store remote tuple in the slot */
711  ExecStoreTuple(localslot->tts_tuple, remoteslot, InvalidBuffer, false);
712  slot_modify_cstrings(remoteslot, rel, newtup.values, newtup.changed);
713  MemoryContextSwitchTo(oldctx);
714 
715  EvalPlanQualSetSlot(&epqstate, remoteslot);
716 
717  /* Do the actual update. */
718  ExecSimpleRelationUpdate(estate, &epqstate, localslot, remoteslot);
719  }
720  else
721  {
722  /*
723  * The tuple to be updated could not be found.
724  *
725  * TODO what to do here, change the log level to LOG perhaps?
726  */
727  elog(DEBUG1,
728  "logical replication did not find row for update "
729  "in replication target relation \"%s\"",
731  }
732 
733  /* Cleanup. */
736 
737  /* Handle queued AFTER triggers. */
738  AfterTriggerEndQuery(estate);
739 
740  EvalPlanQualEnd(&epqstate);
741  ExecResetTupleTable(estate->es_tupleTable, false);
742  FreeExecutorState(estate);
743 
745 
747 }
748 
749 /*
750  * Handle DELETE message.
751  *
752  * TODO: FDW support
753  */
754 static void
756 {
758  LogicalRepTupleData oldtup;
759  LogicalRepRelId relid;
760  Oid idxoid;
761  EState *estate;
762  EPQState epqstate;
763  TupleTableSlot *remoteslot;
764  TupleTableSlot *localslot;
765  bool found;
766  MemoryContext oldctx;
767 
769 
770  relid = logicalrep_read_delete(s, &oldtup);
773  {
774  /*
775  * The relation can't become interesting in the middle of the
776  * transaction so it's safe to unlock it.
777  */
779  return;
780  }
781 
782  /* Check if we can do the delete. */
784 
785  /* Initialize the executor state. */
786  estate = create_estate_for_relation(rel);
787  remoteslot = ExecInitExtraTupleSlot(estate);
789  localslot = ExecInitExtraTupleSlot(estate);
791  EvalPlanQualInit(&epqstate, estate, NULL, NIL, -1);
792 
795 
796  /* Find the tuple using the replica identity index. */
798  slot_store_cstrings(remoteslot, rel, oldtup.values);
799  MemoryContextSwitchTo(oldctx);
800 
801  /*
802  * Try to find tuple using either replica identity index, primary key
803  * or if needed, sequential scan.
804  */
805  idxoid = GetRelationIdentityOrPK(rel->localrel);
806  Assert(OidIsValid(idxoid) ||
808 
809  if (OidIsValid(idxoid))
810  found = RelationFindReplTupleByIndex(rel->localrel, idxoid,
812  remoteslot, localslot);
813  else
815  remoteslot, localslot);
816  /* If found delete it. */
817  if (found)
818  {
819  EvalPlanQualSetSlot(&epqstate, localslot);
820 
821  /* Do the actual delete. */
822  ExecSimpleRelationDelete(estate, &epqstate, localslot);
823  }
824  else
825  {
826  /* The tuple to be deleted could not be found.*/
827  ereport(DEBUG1,
828  (errmsg("logical replication could not find row for delete "
829  "in replication target %s",
831  }
832 
833  /* Cleanup. */
836 
837  /* Handle queued AFTER triggers. */
838  AfterTriggerEndQuery(estate);
839 
840  EvalPlanQualEnd(&epqstate);
841  ExecResetTupleTable(estate->es_tupleTable, false);
842  FreeExecutorState(estate);
843 
845 
847 }
848 
849 
850 /*
851  * Logical replication protocol message dispatcher.
852  */
853 static void
855 {
856  char action = pq_getmsgbyte(s);
857 
858  switch (action)
859  {
860  /* BEGIN */
861  case 'B':
863  break;
864  /* COMMIT */
865  case 'C':
867  break;
868  /* INSERT */
869  case 'I':
871  break;
872  /* UPDATE */
873  case 'U':
875  break;
876  /* DELETE */
877  case 'D':
879  break;
880  /* RELATION */
881  case 'R':
883  break;
884  /* TYPE */
885  case 'Y':
887  break;
888  /* ORIGIN */
889  case 'O':
891  break;
892  default:
893  ereport(ERROR,
894  (errcode(ERRCODE_PROTOCOL_VIOLATION),
895  errmsg("invalid logical replication message type %c", action)));
896  }
897 }
898 
899 /*
900  * Figure out which write/flush positions to report to the walsender process.
901  *
902  * We can't simply report back the last LSN the walsender sent us because the
903  * local transaction might not yet be flushed to disk locally. Instead we
904  * build a list that associates local with remote LSNs for every commit. When
905  * reporting back the flush position to the sender we iterate that list and
906  * check which entries on it are already locally flushed. Those we can report
907  * as having been flushed.
908  *
909  * The have_pending_txes is true if there are outstanding transactions that
910  * need to be flushed.
911  */
912 static void
914  bool *have_pending_txes)
915 {
916  dlist_mutable_iter iter;
917  XLogRecPtr local_flush = GetFlushRecPtr();
918 
919  *write = InvalidXLogRecPtr;
920  *flush = InvalidXLogRecPtr;
921 
922  dlist_foreach_modify(iter, &lsn_mapping)
923  {
924  FlushPosition *pos =
925  dlist_container(FlushPosition, node, iter.cur);
926 
927  *write = pos->remote_end;
928 
929  if (pos->local_end <= local_flush)
930  {
931  *flush = pos->remote_end;
932  dlist_delete(iter.cur);
933  pfree(pos);
934  }
935  else
936  {
937  /*
938  * Don't want to uselessly iterate over the rest of the list which
939  * could potentially be long. Instead get the last element and
940  * grab the write position from there.
941  */
942  pos = dlist_tail_element(FlushPosition, node,
943  &lsn_mapping);
944  *write = pos->remote_end;
945  *have_pending_txes = true;
946  return;
947  }
948  }
949 
950  *have_pending_txes = !dlist_is_empty(&lsn_mapping);
951 }
952 
953 /*
954  * Store current remote/local lsn pair in the tracking list.
955  */
956 static void
958 {
959  FlushPosition *flushpos;
960 
961  /* Need to do this in permanent context */
962  MemoryContextSwitchTo(ApplyCacheContext);
963 
964  /* Track commit lsn */
965  flushpos = (FlushPosition *) palloc(sizeof(FlushPosition));
966  flushpos->local_end = XactLastCommitEnd;
967  flushpos->remote_end = remote_lsn;
968 
969  dlist_push_tail(&lsn_mapping, &flushpos->node);
970  MemoryContextSwitchTo(ApplyContext);
971 }
972 
973 
974 /* Update statistics of the worker. */
975 static void
977 {
979  MyLogicalRepWorker->last_send_time = send_time;
981  if (reply)
982  {
984  MyLogicalRepWorker->reply_time = send_time;
985  }
986 }
987 
988 /*
989  * Apply main loop.
990  */
991 static void
993 {
994  /* Init the ApplyContext which we use for easier cleanup. */
996  "ApplyContext",
1000 
1001  /* mark as idle, before starting to loop */
1003 
1004  while (!got_SIGTERM)
1005  {
1007  int rc;
1008  int len;
1009  char *buf = NULL;
1010  bool endofstream = false;
1011  TimestampTz last_recv_timestamp = GetCurrentTimestamp();
1012  bool ping_sent = false;
1013 
1014  MemoryContextSwitchTo(ApplyContext);
1015 
1016  len = walrcv_receive(wrconn, &buf, &fd);
1017 
1018  if (len != 0)
1019  {
1020  /* Process the data */
1021  for (;;)
1022  {
1024 
1025  if (len == 0)
1026  {
1027  break;
1028  }
1029  else if (len < 0)
1030  {
1031  ereport(LOG,
1032  (errmsg("data stream from publisher has ended")));
1033  endofstream = true;
1034  break;
1035  }
1036  else
1037  {
1038  int c;
1039  StringInfoData s;
1040 
1041  /* Reset timeout. */
1042  last_recv_timestamp = GetCurrentTimestamp();
1043  ping_sent = false;
1044 
1045  /* Ensure we are reading the data into our memory context. */
1046  MemoryContextSwitchTo(ApplyContext);
1047 
1048  s.data = buf;
1049  s.len = len;
1050  s.cursor = 0;
1051  s.maxlen = -1;
1052 
1053  c = pq_getmsgbyte(&s);
1054 
1055  if (c == 'w')
1056  {
1057  XLogRecPtr start_lsn;
1058  XLogRecPtr end_lsn;
1059  TimestampTz send_time;
1060 
1061  start_lsn = pq_getmsgint64(&s);
1062  end_lsn = pq_getmsgint64(&s);
1063  send_time = pq_getmsgint64(&s);
1064 
1065  if (last_received < start_lsn)
1066  last_received = start_lsn;
1067 
1068  if (last_received < end_lsn)
1069  last_received = end_lsn;
1070 
1071  UpdateWorkerStats(last_received, send_time, false);
1072 
1073  apply_dispatch(&s);
1074  }
1075  else if (c == 'k')
1076  {
1077  XLogRecPtr end_lsn;
1079  bool reply_requested;
1080 
1081  end_lsn = pq_getmsgint64(&s);
1082  timestamp = pq_getmsgint64(&s);
1083  reply_requested = pq_getmsgbyte(&s);
1084 
1085  if (last_received < end_lsn)
1086  last_received = end_lsn;
1087 
1088  send_feedback(last_received, reply_requested, false);
1089  UpdateWorkerStats(last_received, timestamp, true);
1090  }
1091  /* other message types are purposefully ignored */
1092  }
1093 
1094  len = walrcv_receive(wrconn, &buf, &fd);
1095  }
1096 
1097  /* confirm all writes at once */
1098  send_feedback(last_received, false, false);
1099  }
1100 
1101  if (!in_remote_transaction)
1102  {
1103  /*
1104  * If we didn't get any transactions for a while there might be
1105  * unconsumed invalidation messages in the queue, consume them now.
1106  */
1108  if (!MySubscriptionValid)
1110 
1111  /* Process any table synchronization changes. */
1112  process_syncing_tables(last_received);
1113  }
1114 
1115  /* Cleanup the memory. */
1118 
1119  /* Check if we need to exit the streaming loop. */
1120  if (endofstream)
1121  {
1122  TimeLineID tli;
1123  walrcv_endstreaming(wrconn, &tli);
1124  break;
1125  }
1126 
1127  /*
1128  * Wait for more data or latch.
1129  */
1133  fd, NAPTIME_PER_CYCLE,
1135 
1136  /* Emergency bailout if postmaster has died */
1137  if (rc & WL_POSTMASTER_DEATH)
1138  proc_exit(1);
1139 
1140  if (rc & WL_TIMEOUT)
1141  {
1142  /*
1143  * We didn't receive anything new. If we haven't heard
1144  * anything from the server for more than
1145  * wal_receiver_timeout / 2, ping the server. Also, if
1146  * it's been longer than wal_receiver_status_interval
1147  * since the last update we sent, send a status update to
1148  * the master anyway, to report any progress in applying
1149  * WAL.
1150  */
1151  bool requestReply = false;
1152 
1153  /*
1154  * Check if time since last receive from standby has
1155  * reached the configured limit.
1156  */
1157  if (wal_receiver_timeout > 0)
1158  {
1160  TimestampTz timeout;
1161 
1162  timeout =
1163  TimestampTzPlusMilliseconds(last_recv_timestamp,
1165 
1166  if (now >= timeout)
1167  ereport(ERROR,
1168  (errmsg("terminating logical replication worker due to timeout")));
1169 
1170  /*
1171  * We didn't receive anything new, for half of
1172  * receiver replication timeout. Ping the server.
1173  */
1174  if (!ping_sent)
1175  {
1176  timeout = TimestampTzPlusMilliseconds(last_recv_timestamp,
1177  (wal_receiver_timeout / 2));
1178  if (now >= timeout)
1179  {
1180  requestReply = true;
1181  ping_sent = true;
1182  }
1183  }
1184  }
1185 
1186  send_feedback(last_received, requestReply, requestReply);
1187  }
1188 
1190  }
1191 }
1192 
1193 /*
1194  * Send a Standby Status Update message to server.
1195  *
1196  * 'recvpos' is the latest LSN we've received data to, force is set if we need
1197  * to send a response to avoid timeouts.
1198  */
1199 static void
1200 send_feedback(XLogRecPtr recvpos, bool force, bool requestReply)
1201 {
1202  static StringInfo reply_message = NULL;
1203  static TimestampTz send_time = 0;
1204 
1205  static XLogRecPtr last_recvpos = InvalidXLogRecPtr;
1206  static XLogRecPtr last_writepos = InvalidXLogRecPtr;
1207  static XLogRecPtr last_flushpos = InvalidXLogRecPtr;
1208 
1209  XLogRecPtr writepos;
1210  XLogRecPtr flushpos;
1211  TimestampTz now;
1212  bool have_pending_txes;
1213 
1214  /*
1215  * If the user doesn't want status to be reported to the publisher, be
1216  * sure to exit before doing anything at all.
1217  */
1218  if (!force && wal_receiver_status_interval <= 0)
1219  return;
1220 
1221  /* It's legal to not pass a recvpos */
1222  if (recvpos < last_recvpos)
1223  recvpos = last_recvpos;
1224 
1225  get_flush_position(&writepos, &flushpos, &have_pending_txes);
1226 
1227  /*
1228  * No outstanding transactions to flush, we can report the latest
1229  * received position. This is important for synchronous replication.
1230  */
1231  if (!have_pending_txes)
1232  flushpos = writepos = recvpos;
1233 
1234  if (writepos < last_writepos)
1235  writepos = last_writepos;
1236 
1237  if (flushpos < last_flushpos)
1238  flushpos = last_flushpos;
1239 
1240  now = GetCurrentTimestamp();
1241 
1242  /* if we've already reported everything we're good */
1243  if (!force &&
1244  writepos == last_writepos &&
1245  flushpos == last_flushpos &&
1246  !TimestampDifferenceExceeds(send_time, now,
1248  return;
1249  send_time = now;
1250 
1251  if (!reply_message)
1252  {
1253  MemoryContext oldctx = MemoryContextSwitchTo(ApplyCacheContext);
1254  reply_message = makeStringInfo();
1255  MemoryContextSwitchTo(oldctx);
1256  }
1257  else
1258  resetStringInfo(reply_message);
1259 
1260  pq_sendbyte(reply_message, 'r');
1261  pq_sendint64(reply_message, recvpos); /* write */
1262  pq_sendint64(reply_message, flushpos); /* flush */
1263  pq_sendint64(reply_message, writepos); /* apply */
1264  pq_sendint64(reply_message, now); /* sendTime */
1265  pq_sendbyte(reply_message, requestReply); /* replyRequested */
1266 
1267  elog(DEBUG2, "sending feedback (force %d) to recv %X/%X, write %X/%X, flush %X/%X",
1268  force,
1269  (uint32) (recvpos >> 32), (uint32) recvpos,
1270  (uint32) (writepos >> 32), (uint32) writepos,
1271  (uint32) (flushpos >> 32), (uint32) flushpos
1272  );
1273 
1274  walrcv_send(wrconn, reply_message->data, reply_message->len);
1275 
1276  if (recvpos > last_recvpos)
1277  last_recvpos = recvpos;
1278  if (writepos > last_writepos)
1279  last_writepos = writepos;
1280  if (flushpos > last_flushpos)
1281  last_flushpos = flushpos;
1282 }
1283 
1284 
1285 /*
1286  * Reread subscription info and exit on change.
1287  */
1288 static void
1290 {
1291  MemoryContext oldctx;
1293  bool started_tx = false;
1294 
1295  /* This function might be called inside or outside of transaction. */
1296  if (!IsTransactionState())
1297  {
1299  started_tx = true;
1300  }
1301 
1302  /* Ensure allocations in permanent context. */
1303  oldctx = MemoryContextSwitchTo(ApplyCacheContext);
1304 
1305  newsub = GetSubscription(MyLogicalRepWorker->subid, true);
1306 
1307  /*
1308  * Exit if the subscription was removed.
1309  * This normally should not happen as the worker gets killed
1310  * during DROP SUBSCRIPTION.
1311  */
1312  if (!newsub)
1313  {
1314  ereport(LOG,
1315  (errmsg("logical replication worker for subscription \"%s\" will "
1316  "stop because the subscription was removed",
1317  MySubscription->name)));
1318 
1319  walrcv_disconnect(wrconn);
1320  proc_exit(0);
1321  }
1322 
1323  /*
1324  * Exit if connection string was changed. The launcher will start
1325  * new worker.
1326  */
1327  if (strcmp(newsub->conninfo, MySubscription->conninfo) != 0)
1328  {
1329  ereport(LOG,
1330  (errmsg("logical replication worker for subscription \"%s\" will "
1331  "restart because the connection information was changed",
1332  MySubscription->name)));
1333 
1334  walrcv_disconnect(wrconn);
1335  proc_exit(0);
1336  }
1337 
1338  /*
1339  * Exit if subscription name was changed (it's used for
1340  * fallback_application_name). The launcher will start new worker.
1341  */
1342  if (strcmp(newsub->name, MySubscription->name) != 0)
1343  {
1344  ereport(LOG,
1345  (errmsg("logical replication worker for subscription \"%s\" will "
1346  "restart because subscription was renamed",
1347  MySubscription->name)));
1348 
1349  walrcv_disconnect(wrconn);
1350  proc_exit(0);
1351  }
1352 
1353  /*
1354  * Exit if publication list was changed. The launcher will start
1355  * new worker.
1356  */
1357  if (!equal(newsub->publications, MySubscription->publications))
1358  {
1359  ereport(LOG,
1360  (errmsg("logical replication worker for subscription \"%s\" will "
1361  "restart because subscription's publications were changed",
1362  MySubscription->name)));
1363 
1364  walrcv_disconnect(wrconn);
1365  proc_exit(0);
1366  }
1367 
1368  /*
1369  * Exit if the subscription was disabled.
1370  * This normally should not happen as the worker gets killed
1371  * during ALTER SUBSCRIPTION ... DISABLE.
1372  */
1373  if (!newsub->enabled)
1374  {
1375  ereport(LOG,
1376  (errmsg("logical replication worker for subscription \"%s\" will "
1377  "stop because the subscription was disabled",
1378  MySubscription->name)));
1379 
1380  walrcv_disconnect(wrconn);
1381  proc_exit(0);
1382  }
1383 
1384  /* Check for other changes that should never happen too. */
1385  if (newsub->dbid != MySubscription->dbid ||
1386  strcmp(newsub->slotname, MySubscription->slotname) != 0)
1387  {
1388  elog(ERROR, "subscription %u changed unexpectedly",
1390  }
1391 
1392  /* Clean old subscription info and switch to new one. */
1393  FreeSubscription(MySubscription);
1394  MySubscription = newsub;
1395 
1396  MemoryContextSwitchTo(oldctx);
1397 
1398  if (started_tx)
1400 
1401  MySubscriptionValid = true;
1402 }
1403 
1404 /*
1405  * Callback from subscription syscache invalidation.
1406  */
1407 static void
1408 subscription_change_cb(Datum arg, int cacheid, uint32 hashvalue)
1409 {
1410  MySubscriptionValid = false;
1411 }
1412 
1413 
1414 /* Logical Replication Apply worker entry point */
1415 void
1417 {
1418  int worker_slot = DatumGetObjectId(main_arg);
1419  MemoryContext oldctx;
1420  char originname[NAMEDATALEN];
1421  XLogRecPtr origin_startpos;
1422  char *myslotname;
1424 
1425  /* Attach to slot */
1426  logicalrep_worker_attach(worker_slot);
1427 
1428  /* Setup signal handling */
1431 
1432  /* Initialise stats to a sanish value */
1435 
1436  /* Make it easy to identify our processes. */
1437  SetConfigOption("application_name", MyBgworkerEntry->bgw_name,
1439 
1440  /* Load the libpq-specific functions */
1441  load_file("libpqwalreceiver", false);
1442 
1445  "logical replication apply");
1446 
1447  /* Run as replica session replication role. */
1448  SetConfigOption("session_replication_role", "replica",
1450 
1451  /* Connect to our database. */
1454 
1455  /* Load the subscription into persistent memory context. */
1457  ApplyCacheContext = AllocSetContextCreate(CacheMemoryContext,
1458  "ApplyCacheContext",
1461  oldctx = MemoryContextSwitchTo(ApplyCacheContext);
1462  MySubscription = GetSubscription(MyLogicalRepWorker->subid, false);
1463  MySubscriptionValid = true;
1464  MemoryContextSwitchTo(oldctx);
1465 
1466  if (!MySubscription->enabled)
1467  {
1468  ereport(LOG,
1469  (errmsg("logical replication worker for subscription \"%s\" will not "
1470  "start because the subscription was disabled during startup",
1471  MySubscription->name)));
1472 
1473  proc_exit(0);
1474  }
1475 
1476  /* Keep us informed about subscription changes. */
1479  (Datum) 0);
1480 
1481  if (am_tablesync_worker())
1482  elog(LOG, "logical replication sync for subscription %s, table %s started",
1483  MySubscription->name, get_rel_name(MyLogicalRepWorker->relid));
1484  else
1485  elog(LOG, "logical replication apply for subscription %s started",
1486  MySubscription->name);
1487 
1489 
1490  /* Connect to the origin and start the replication. */
1491  elog(DEBUG1, "connecting to publisher using connection string \"%s\"",
1492  MySubscription->conninfo);
1493 
1494  if (am_tablesync_worker())
1495  {
1496  char *syncslotname;
1497 
1498  /* This is table synchroniation worker, call initial sync. */
1499  syncslotname = LogicalRepSyncTableStart(&origin_startpos);
1500 
1501  /* The slot name needs to be allocated in permanent memory context. */
1502  oldctx = MemoryContextSwitchTo(ApplyCacheContext);
1503  myslotname = pstrdup(syncslotname);
1504  MemoryContextSwitchTo(oldctx);
1505 
1506  pfree(syncslotname);
1507  }
1508  else
1509  {
1510  /* This is main apply worker */
1511  RepOriginId originid;
1512  TimeLineID startpointTLI;
1513  char *err;
1514  int server_version;
1515 
1516  myslotname = MySubscription->slotname;
1517 
1518  /* Setup replication origin tracking. */
1520  snprintf(originname, sizeof(originname), "pg_%u", MySubscription->oid);
1521  originid = replorigin_by_name(originname, true);
1522  if (!OidIsValid(originid))
1523  originid = replorigin_create(originname);
1524  replorigin_session_setup(originid);
1525  replorigin_session_origin = originid;
1526  origin_startpos = replorigin_session_get_progress(false);
1528 
1529  wrconn = walrcv_connect(MySubscription->conninfo, true, myslotname,
1530  &err);
1531  if (wrconn == NULL)
1532  ereport(ERROR,
1533  (errmsg("could not connect to the publisher: %s", err)));
1534 
1535  /*
1536  * We don't really use the output identify_system for anything
1537  * but it does some initializations on the upstream so let's still
1538  * call it.
1539  */
1540  (void) walrcv_identify_system(wrconn, &startpointTLI,
1541  &server_version);
1542 
1543  }
1544 
1545  /*
1546  * Setup callback for syscache so that we know when something
1547  * changes in the subscription relation state.
1548  */
1551  (Datum) 0);
1552 
1553  /* Build logical replication streaming options. */
1554  options.logical = true;
1555  options.startpoint = origin_startpos;
1556  options.slotname = myslotname;
1557  options.proto.logical.proto_version = LOGICALREP_PROTO_VERSION_NUM;
1558  options.proto.logical.publication_names = MySubscription->publications;
1559 
1560  /* Start normal logical streaming replication. */
1561  walrcv_startstreaming(wrconn, &options);
1562 
1563  /* Run the main loop. */
1564  LogicalRepApplyLoop(origin_startpos);
1565 
1566  walrcv_disconnect(wrconn);
1567 
1568  /* We should only get here if we received SIGTERM */
1569  proc_exit(0);
1570 }
void ExecSimpleRelationInsert(EState *estate, TupleTableSlot *slot)
Subscription * MySubscription
Definition: worker.c:109
static void apply_handle_type(StringInfo s)
Definition: worker.c:510
static bool should_apply_changes_for_rel(LogicalRepRelMapEntry *rel)
Definition: worker.c:135
#define NIL
Definition: pg_list.h:69
#define LOGICALREP_PROTO_VERSION_NUM
Definition: logicalproto.h:28
TupleTableSlot * ExecStoreTuple(HeapTuple tuple, TupleTableSlot *slot, Buffer buffer, bool shouldFree)
Definition: execTuples.c:320
static EState * create_estate_for_relation(LogicalRepRelMapEntry *rel)
Definition: worker.c:177
static Oid GetRelationIdentityOrPK(Relation rel)
Definition: worker.c:524
void InitResultRelInfo(ResultRelInfo *resultRelInfo, Relation resultRelationDesc, Index resultRelationIndex, Relation partition_root, int instrument_options)
Definition: execMain.c:1255
static void send_feedback(XLogRecPtr recvpos, bool force, bool requestReply)
Definition: worker.c:1200
WalReceiverConn * wrconn
Definition: worker.c:107
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
#define walrcv_endstreaming(conn, next_tli)
Definition: walreceiver.h:254
TupleTableSlot * ExecInitExtraTupleSlot(EState *estate)
Definition: execTuples.c:852
#define DEBUG1
Definition: elog.h:25
dlist_node * cur
Definition: ilist.h:180
static void store_flush_position(XLogRecPtr remote_lsn)
Definition: worker.c:957
MemoryContext ApplyCacheContext
Definition: worker.c:105
uint32 TimeLineID
Definition: xlogdefs.h:45
LogicalRepRelId logicalrep_read_delete(StringInfo in, LogicalRepTupleData *oldtup)
Definition: proto.c:277
void AcceptInvalidationMessages(void)
Definition: inval.c:672
static XLogRecPtr remote_final_lsn
Definition: worker.c:113
Oid RelationGetReplicaIndex(Relation relation)
Definition: relcache.c:4665
void pq_sendbyte(StringInfo buf, int byt)
Definition: pqformat.c:105
#define WL_TIMEOUT
Definition: latch.h:127
static void apply_handle_insert(StringInfo s)
Definition: worker.c:540
#define dlist_foreach_modify(iter, lhead)
Definition: ilist.h:524
static dlist_head lsn_mapping
Definition: worker.c:96
bool equal(const void *a, const void *b)
Definition: equalfuncs.c:2946
#define RelationGetDescr(relation)
Definition: rel.h:429
void process_syncing_tables(XLogRecPtr current_lsn)
Definition: tablesync.c:412
dlist_node node
Definition: worker.c:91
#define write(a, b, c)
Definition: win32.h:19
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1569
void pgstat_report_activity(BackendState state, const char *cmd_str)
Definition: pgstat.c:2806
int64 timestamp
PGPROC * MyProc
Definition: proc.c:67
void logicalrep_read_begin(StringInfo in, LogicalRepBeginData *begin_data)
Definition: proto.c:57
int64 TimestampTz
Definition: timestamp.h:39
union WalRcvStreamOptions::@54 proto
LogicalRepRelation * rel
Definition: worker.c:100
ResourceOwner CurrentResourceOwner
Definition: resowner.c:138
#define DatumGetObjectId(X)
Definition: postgres.h:506
char * pstrdup(const char *in)
Definition: mcxt.c:1077
void CommitTransactionCommand(void)
Definition: xact.c:2747
static void UpdateWorkerStats(XLogRecPtr last_lsn, TimestampTz send_time, bool reply)
Definition: worker.c:976
XLogRecPtr XactLastCommitEnd
Definition: xlog.c:338
static void dlist_push_tail(dlist_head *head, dlist_node *node)
Definition: ilist.h:317
StringInfo makeStringInfo(void)
Definition: stringinfo.c:29
static void reread_subscription(void)
Definition: worker.c:1289
#define walrcv_receive(conn, buffer, wait_fd)
Definition: walreceiver.h:256
LogicalRepRelation * logicalrep_read_rel(StringInfo in)
Definition: proto.c:324
Expr * expression_planner(Expr *expr)
Definition: planner.c:5382
TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: execTuples.c:439
Form_pg_attribute * attrs
Definition: tupdesc.h:74
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
TimestampTz last_send_time
#define InvalidBuffer
Definition: buf.h:25
uint16 RepOriginId
Definition: xlogdefs.h:51
XLogRecPtr last_lsn
#define walrcv_startstreaming(conn, options)
Definition: walreceiver.h:252
void proc_exit(int code)
Definition: ipc.c:99
XLogRecPtr replorigin_session_get_progress(bool flush)
Definition: origin.c:1107
XLogRecPtr remote_end
Definition: worker.c:93
int errcode(int sqlerrcode)
Definition: elog.c:575
char * format_type_be(Oid type_oid)
Definition: format_type.c:94
void logicalrep_rel_close(LogicalRepRelMapEntry *rel, LOCKMODE lockmode)
Definition: relation.c:374
BackgroundWorker * MyBgworkerEntry
Definition: postmaster.c:189
Datum * tts_values
Definition: tuptable.h:125
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
#define WL_SOCKET_READABLE
Definition: latch.h:125
XLogRecPtr GetFlushRecPtr(void)
Definition: xlog.c:8212
void PopActiveSnapshot(void)
Definition: snapmgr.c:807
Oid logicalrep_typmap_getid(Oid remoteid)
Definition: relation.c:448
void replorigin_session_setup(RepOriginId node)
Definition: origin.c:980
void ResetLatch(volatile Latch *latch)
Definition: latch.c:461
List * es_range_table
Definition: execnodes.h:374
#define LOG
Definition: elog.h:26
Form_pg_class rd_rel
Definition: rel.h:114
unsigned int Oid
Definition: postgres_ext.h:31
struct SlotErrCallbackArg SlotErrCallbackArg
char * LogicalRepSyncTableStart(XLogRecPtr *origin_startpos)
Definition: tablesync.c:693
int wal_receiver_status_interval
Definition: walreceiver.c:73
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1648
struct ErrorContextCallback * previous
Definition: elog.h:238
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:300
#define OidIsValid(objectId)
Definition: c.h:538
XLogRecPtr last_lsn
Definition: walsender.c:206
bool RelationFindReplTupleByIndex(Relation rel, Oid idxoid, LockTupleMode lockmode, TupleTableSlot *searchslot, TupleTableSlot *outslot)
static int fd(const char *x, int i)
Definition: preproc-init.c:105
int natts
Definition: tupdesc.h:73
RepOriginId replorigin_by_name(char *roname, bool missing_ok)
Definition: origin.c:206
#define ALLOCSET_DEFAULT_MINSIZE
Definition: memutils.h:162
int wal_receiver_timeout
Definition: walreceiver.c:74
Latch procLatch
Definition: proc.h:98
static void get_flush_position(XLogRecPtr *write, XLogRecPtr *flush, bool *have_pending_txes)
Definition: worker.c:913
void ExecOpenIndices(ResultRelInfo *resultRelInfo, bool speculative)
Definition: execIndexing.c:149
void EvalPlanQualEnd(EPQState *epqstate)
Definition: execMain.c:3069
LogicalRepRelId logicalrep_read_insert(StringInfo in, LogicalRepTupleData *newtup)
Definition: proto.c:160
ErrorContextCallback * error_context_stack
Definition: elog.c:88
static void slot_fill_defaults(LogicalRepRelMapEntry *rel, EState *estate, TupleTableSlot *slot)
Definition: worker.c:216
#define list_make1(x1)
Definition: pg_list.h:133
#define NAMEDATALEN
void FreeExecutorState(EState *estate)
Definition: execUtils.c:169
Subscription * GetSubscription(Oid subid, bool missing_ok)
#define GetPerTupleExprContext(estate)
Definition: executor.h:339
void logicalrep_relmap_update(LogicalRepRelation *remoterel)
Definition: relation.c:166
static StringInfoData reply_message
Definition: walreceiver.c:110
static void subscription_change_cb(Datum arg, int cacheid, uint32 hashvalue)
Definition: worker.c:1408
#define dlist_container(type, membername, ptr)
Definition: ilist.h:477
ExprState * ExecInitExpr(Expr *node, PlanState *parent)
Definition: execQual.c:4267
void pfree(void *pointer)
Definition: mcxt.c:950
#define dlist_tail_element(type, membername, lhead)
Definition: ilist.h:496
#define REPLICA_IDENTITY_FULL
Definition: pg_class.h:179
#define ExecEvalExpr(expr, econtext, isNull)
Definition: executor.h:73
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:62
#define ERROR
Definition: elog.h:43
static bool ensure_transaction(void)
Definition: worker.c:151
LogicalRepRelation remoterel
#define NAPTIME_PER_CYCLE
Definition: worker.c:87
bool in_remote_transaction
Definition: worker.c:112
void logicalrep_read_typ(StringInfo in, LogicalRepTyp *ltyp)
Definition: proto.c:376
Definition: guc.h:75
static void slot_store_cstrings(TupleTableSlot *slot, LogicalRepRelMapEntry *rel, char **values)
Definition: worker.c:296
static volatile sig_atomic_t got_SIGTERM
Definition: autovacuum.c:140
XLogRecPtr reply_lsn
static bool am_tablesync_worker(void)
static void apply_handle_delete(StringInfo s)
Definition: worker.c:755
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:165
#define DEBUG2
Definition: elog.h:24
XLogRecPtr replorigin_session_origin_lsn
Definition: origin.c:151
char * c
#define walrcv_identify_system(conn, primary_tli, server_version)
Definition: walreceiver.h:248
void logicalrep_worker_attach(int slot)
Definition: launcher.c:445
#define NoLock
Definition: lockdefs.h:34
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition: guc.c:6651
static char * buf
Definition: pg_test_fsync.c:65
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:728
TimestampTz replorigin_session_origin_timestamp
Definition: origin.c:152
bool changed[MaxTupleAttributeNumber]
Definition: logicalproto.h:34
bool * tts_isnull
Definition: tuptable.h:126
void ExecSimpleRelationDelete(EState *estate, EPQState *epqstate, TupleTableSlot *searchslot)
ResultRelInfo * es_result_relations
Definition: execnodes.h:384
#define RowExclusiveLock
Definition: lockdefs.h:38
#define RelationGetRelationName(relation)
Definition: rel.h:437
XLogRecPtr startpoint
Definition: walreceiver.h:147
FormData_pg_attribute * Form_pg_attribute
Definition: pg_attribute.h:184
void resetStringInfo(StringInfo str)
Definition: stringinfo.c:94
unsigned int uint32
Definition: c.h:268
int pgsocket
Definition: port.h:22
List * publications
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
static void apply_handle_begin(StringInfo s)
Definition: worker.c:418
RepOriginId replorigin_create(char *roname)
Definition: origin.c:235
void BackgroundWorkerInitializeConnectionByOid(Oid dboid, Oid useroid)
Definition: postmaster.c:5475
static void dlist_delete(dlist_node *node)
Definition: ilist.h:358
LogicalRepRelMapEntry * logicalrep_rel_open(LogicalRepRelId remoteid, LOCKMODE lockmode)
Definition: relation.c:231
TupleTableSlot * es_trig_tuple_slot
Definition: execnodes.h:390
#define ereport(elevel, rest)
Definition: elog.h:122
void getTypeInputInfo(Oid type, Oid *typInput, Oid *typIOParam)
Definition: lsyscache.c:2567
void slot_getallattrs(TupleTableSlot *slot)
Definition: heaptuple.c:1239
MemoryContext TopMemoryContext
Definition: mcxt.c:43
TriggerDesc * ri_TrigDesc
Definition: execnodes.h:341
EState * CreateExecutorState(void)
Definition: execUtils.c:73
static void check_relation_updatable(LogicalRepRelMapEntry *rel)
Definition: worker.c:600
static MemoryContext ApplyContext
Definition: worker.c:104
static char ** options
XLogRecPtr final_lsn
Definition: logicalproto.h:65
#define DLIST_STATIC_INIT(name)
Definition: ilist.h:248
static void apply_handle_commit(StringInfo s)
Definition: worker.c:440
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:67
TupleDesc tts_tupleDescriptor
Definition: tuptable.h:121
Node * build_column_default(Relation rel, int attrno)
#define SUBREL_STATE_SYNCDONE
#define WL_POSTMASTER_DEATH
Definition: latch.h:128
List * es_tupleTable
Definition: execnodes.h:401
MemoryContext AllocSetContextCreate(MemoryContext parent, const char *name, Size minContextSize, Size initBlockSize, Size maxBlockSize)
Definition: aset.c:322
void CacheRegisterSyscacheCallback(int cacheid, SyscacheCallbackFunction func, Datum arg)
Definition: inval.c:1381
void ExecResetTupleTable(List *tupleTable, bool shouldFree)
Definition: execTuples.c:156
static void apply_handle_update(StringInfo s)
Definition: worker.c:634
uintptr_t Datum
Definition: postgres.h:372
void CommandCounterIncrement(void)
Definition: xact.c:922
void ExecSetSlotDescriptor(TupleTableSlot *slot, TupleDesc tupdesc)
Definition: execTuples.c:247
#define PGINVALID_SOCKET
Definition: port.h:24
void logicalrep_worker_sigterm(SIGNAL_ARGS)
Definition: launcher.c:495
int es_num_result_relations
Definition: execnodes.h:385
void EvalPlanQualInit(EPQState *epqstate, EState *estate, Plan *subplan, List *auxrowmarks, int epqParam)
Definition: execMain.c:2658
static void apply_handle_relation(StringInfo s)
Definition: worker.c:495
#define TimestampTzPlusMilliseconds(tz, ms)
Definition: timestamp.h:56
XLogRecPtr local_end
Definition: worker.c:92
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:168
int pq_getmsgbyte(StringInfo msg)
Definition: pqformat.c:432
void AfterTriggerBeginQuery(void)
Definition: trigger.c:4150
static void apply_dispatch(StringInfo s)
Definition: worker.c:854
#define makeNode(_type_)
Definition: nodes.h:570
TimestampTz last_recv_time
#define NULL
Definition: c.h:229
uint64 XLogRecPtr
Definition: xlogdefs.h:21
char bgw_name[BGW_MAXLEN]
Definition: bgworker.h:90
#define Assert(condition)
Definition: c.h:675
int WaitLatchOrSocket(volatile Latch *latch, int wakeEvents, pgsocket sock, long timeout, uint32 wait_event_info)
Definition: latch.c:320
RepOriginId replorigin_session_origin
Definition: origin.c:150
static void apply_handle_origin(StringInfo s)
Definition: worker.c:473
void StartTransactionCommand(void)
Definition: xact.c:2677
void load_file(const char *filename, bool restricted)
Definition: dfmgr.c:133
static bool dlist_is_empty(dlist_head *head)
Definition: ilist.h:289
static int server_version
Definition: pg_dumpall.c:80
void CreateCacheMemoryContext(void)
Definition: catcache.c:525
static void slot_store_error_callback(void *arg)
Definition: worker.c:271
LogicalRepRelId logicalrep_read_update(StringInfo in, bool *has_oldtuple, LogicalRepTupleData *oldtup, LogicalRepTupleData *newtup)
Definition: proto.c:211
bool IsTransactionState(void)
Definition: xact.c:350
#define walrcv_disconnect(conn)
Definition: walreceiver.h:264
#define walrcv_send(conn, buffer, nbytes)
Definition: walreceiver.h:258
void logicalrep_read_commit(StringInfo in, LogicalRepCommitData *commit_data)
Definition: proto.c:92
bool MySubscriptionValid
Definition: worker.c:110
char * values[MaxTupleAttributeNumber]
Definition: logicalproto.h:33
#define GetPerTupleMemoryContext(estate)
Definition: executor.h:344
void FreeSubscription(Subscription *sub)
RTEKind rtekind
Definition: parsenodes.h:916
static Datum values[MAXATTR]
Definition: bootstrap.c:162
void AfterTriggerEndQuery(EState *estate)
Definition: trigger.c:4170
void(* callback)(void *arg)
Definition: elog.h:239
static void slot_modify_cstrings(TupleTableSlot *slot, LogicalRepRelMapEntry *rel, char **values, bool *replaces)
Definition: worker.c:360
void * palloc(Size size)
Definition: mcxt.c:849
int errmsg(const char *fmt,...)
Definition: elog.c:797
static void LogicalRepApplyLoop(XLogRecPtr last_received)
Definition: worker.c:992
bool RelationFindReplTupleSeq(Relation rel, LockTupleMode lockmode, TupleTableSlot *searchslot, TupleTableSlot *outslot)
#define ALLOCSET_DEFAULT_INITSIZE
Definition: memutils.h:163
int i
int64 pq_getmsgint64(StringInfo msg)
Definition: pqformat.c:486
#define errcontext
Definition: elog.h:164
void * arg
struct FlushPosition FlushPosition
#define ALLOCSET_DEFAULT_MAXSIZE
Definition: memutils.h:164
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:97
HeapTuple tts_tuple
Definition: tuptable.h:120
#define elog
Definition: elog.h:219
TimestampTz committime
Definition: logicalproto.h:66
XLogRecPtr commit_lsn
Definition: logicalproto.h:72
static color newsub(struct colormap *cm, color co)
Definition: regc_color.c:389
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1694
void pq_sendint64(StringInfo buf, int64 i)
Definition: pqformat.c:271
Datum OidInputFunctionCall(Oid functionId, char *str, Oid typioparam, int32 typmod)
Definition: fmgr.c:2047
#define WL_LATCH_SET
Definition: latch.h:124
#define SUBREL_STATE_READY
#define RelationGetRelid(relation)
Definition: rel.h:417
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1533
void ExecCloseIndices(ResultRelInfo *resultRelInfo)
Definition: execIndexing.c:224
Oid RelationGetPrimaryKeyIndex(Relation relation)
Definition: relcache.c:4644
void ExecSimpleRelationUpdate(EState *estate, EPQState *epqstate, TupleTableSlot *searchslot, TupleTableSlot *slot)
TimestampTz committime
Definition: logicalproto.h:74
void logicalrep_typmap_update(LogicalRepTyp *remotetyp)
Definition: relation.c:417
void ApplyWorkerMain(Datum main_arg)
Definition: worker.c:1416
uint32 LogicalRepRelId
Definition: logicalproto.h:37
TupleTableSlot * ExecStoreVirtualTuple(TupleTableSlot *slot)
Definition: execTuples.c:488
TimestampTz reply_time
#define EvalPlanQualSetSlot(epqstate, slot)
Definition: executor.h:229
void invalidate_syncing_table_states(Datum arg, int cacheid, uint32 hashvalue)
Definition: tablesync.c:185
ResourceOwner ResourceOwnerCreate(ResourceOwner parent, const char *name)
Definition: resowner.c:416
MemoryContext CacheMemoryContext
Definition: mcxt.c:46
void BackgroundWorkerUnblockSignals(void)
Definition: postmaster.c:5504
#define walrcv_connect(conninfo, logical, appname, err)
Definition: walreceiver.h:242
ResultRelInfo * es_result_relation_info
Definition: execnodes.h:386