PostgreSQL Source Code  git master
slotfuncs.c File Reference
#include "postgres.h"
#include "access/htup_details.h"
#include "access/xlog_internal.h"
#include "access/xlogutils.h"
#include "funcapi.h"
#include "miscadmin.h"
#include "replication/decode.h"
#include "replication/logical.h"
#include "replication/slot.h"
#include "utils/builtins.h"
#include "utils/inval.h"
#include "utils/pg_lsn.h"
#include "utils/resowner.h"
Include dependency graph for slotfuncs.c:

Go to the source code of this file.

Macros

#define PG_GET_REPLICATION_SLOTS_COLS   13
 

Functions

static void check_permissions (void)
 
static void create_physical_replication_slot (char *name, bool immediately_reserve, bool temporary, XLogRecPtr restart_lsn)
 
Datum pg_create_physical_replication_slot (PG_FUNCTION_ARGS)
 
static void create_logical_replication_slot (char *name, char *plugin, bool temporary, XLogRecPtr restart_lsn, bool find_startpoint)
 
Datum pg_create_logical_replication_slot (PG_FUNCTION_ARGS)
 
Datum pg_drop_replication_slot (PG_FUNCTION_ARGS)
 
Datum pg_get_replication_slots (PG_FUNCTION_ARGS)
 
static XLogRecPtr pg_physical_replication_slot_advance (XLogRecPtr moveto)
 
static XLogRecPtr pg_logical_replication_slot_advance (XLogRecPtr moveto)
 
Datum pg_replication_slot_advance (PG_FUNCTION_ARGS)
 
static Datum copy_replication_slot (FunctionCallInfo fcinfo, bool logical_slot)
 
Datum pg_copy_logical_replication_slot_a (PG_FUNCTION_ARGS)
 
Datum pg_copy_logical_replication_slot_b (PG_FUNCTION_ARGS)
 
Datum pg_copy_logical_replication_slot_c (PG_FUNCTION_ARGS)
 
Datum pg_copy_physical_replication_slot_a (PG_FUNCTION_ARGS)
 
Datum pg_copy_physical_replication_slot_b (PG_FUNCTION_ARGS)
 

Macro Definition Documentation

◆ PG_GET_REPLICATION_SLOTS_COLS

#define PG_GET_REPLICATION_SLOTS_COLS   13

Function Documentation

◆ check_permissions()

static void check_permissions ( void  )
static

Definition at line 29 of file slotfuncs.c.

References ereport, errcode(), errmsg(), ERROR, GetUserId(), has_rolreplication(), and superuser().

Referenced by copy_replication_slot(), pg_create_logical_replication_slot(), pg_create_physical_replication_slot(), pg_drop_replication_slot(), and pg_replication_slot_advance().

30 {
32  ereport(ERROR,
33  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
34  errmsg("must be superuser or replication role to use replication slots")));
35 }
Oid GetUserId(void)
Definition: miscinit.c:476
int errcode(int sqlerrcode)
Definition: elog.c:610
bool superuser(void)
Definition: superuser.c:46
#define ERROR
Definition: elog.h:43
#define ereport(elevel,...)
Definition: elog.h:144
bool has_rolreplication(Oid roleid)
Definition: miscinit.c:657
int errmsg(const char *fmt,...)
Definition: elog.c:821

◆ copy_replication_slot()

static Datum copy_replication_slot ( FunctionCallInfo  fcinfo,
bool  logical_slot 
)
static

Definition at line 697 of file slotfuncs.c.

References Assert, ReplicationSlotPersistentData::catalog_xmin, check_permissions(), CheckLogicalDecodingRequirements(), CheckSlotRequirements(), ReplicationSlotPersistentData::confirmed_flush, create_logical_replication_slot(), create_physical_replication_slot(), ReplicationSlot::data, ReplicationSlot::effective_catalog_xmin, ReplicationSlot::effective_xmin, elog, ereport, errcode(), errdetail(), errhint(), errmsg(), ERROR, get_call_result_type(), heap_form_tuple(), HeapTupleGetDatum, i, ReplicationSlot::in_use, LSNGetDatum, LW_SHARED, LWLockAcquire(), LWLockRelease(), max_replication_slots, ReplicationSlot::mutex, MyReplicationSlot, ReplicationSlotPersistentData::name, NameGetDatum, NameStr, ReplicationSlotPersistentData::persistency, PG_GETARG_BOOL, PG_GETARG_NAME, PG_NARGS, PG_RETURN_DATUM, plugin, ReplicationSlotPersistentData::plugin, ReplicationSlotCtlData::replication_slots, ReplicationSlotCtl, ReplicationSlotMarkDirty(), ReplicationSlotPersist(), ReplicationSlotRelease(), ReplicationSlotSave(), ReplicationSlotsComputeRequiredLSN(), ReplicationSlotsComputeRequiredXmin(), ReplicationSlotPersistentData::restart_lsn, RS_TEMPORARY, SlotIsLogical, SpinLockAcquire, SpinLockRelease, TYPEFUNC_COMPOSITE, values, wal_segment_size, XLByteToSeg, XLogGetLastRemovedSegno(), XLogRecPtrIsInvalid, and ReplicationSlotPersistentData::xmin.

Referenced by pg_copy_logical_replication_slot_a(), pg_copy_logical_replication_slot_b(), pg_copy_logical_replication_slot_c(), pg_copy_physical_replication_slot_a(), and pg_copy_physical_replication_slot_b().

698 {
699  Name src_name = PG_GETARG_NAME(0);
700  Name dst_name = PG_GETARG_NAME(1);
701  ReplicationSlot *src = NULL;
702  ReplicationSlot first_slot_contents;
703  ReplicationSlot second_slot_contents;
704  XLogRecPtr src_restart_lsn;
705  bool src_islogical;
706  bool temporary;
707  char *plugin;
708  Datum values[2];
709  bool nulls[2];
710  Datum result;
711  TupleDesc tupdesc;
712  HeapTuple tuple;
713 
714  if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
715  elog(ERROR, "return type must be a row type");
716 
718 
719  if (logical_slot)
721  else
723 
724  LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
725 
726  /*
727  * We need to prevent the source slot's reserved WAL from being removed,
728  * but we don't want to lock that slot for very long, and it can advance
729  * in the meantime. So obtain the source slot's data, and create a new
730  * slot using its restart_lsn. Afterwards we lock the source slot again
731  * and verify that the data we copied (name, type) has not changed
732  * incompatibly. No inconvenient WAL removal can occur once the new slot
733  * is created -- but since WAL removal could have occurred before we
734  * managed to create the new slot, we advance the new slot's restart_lsn
735  * to the source slot's updated restart_lsn the second time we lock it.
736  */
737  for (int i = 0; i < max_replication_slots; i++)
738  {
740 
741  if (s->in_use && strcmp(NameStr(s->data.name), NameStr(*src_name)) == 0)
742  {
743  /* Copy the slot contents while holding spinlock */
744  SpinLockAcquire(&s->mutex);
745  first_slot_contents = *s;
746  SpinLockRelease(&s->mutex);
747  src = s;
748  break;
749  }
750  }
751 
752  LWLockRelease(ReplicationSlotControlLock);
753 
754  if (src == NULL)
755  ereport(ERROR,
756  (errcode(ERRCODE_UNDEFINED_OBJECT),
757  errmsg("replication slot \"%s\" does not exist", NameStr(*src_name))));
758 
759  src_islogical = SlotIsLogical(&first_slot_contents);
760  src_restart_lsn = first_slot_contents.data.restart_lsn;
761  temporary = (first_slot_contents.data.persistency == RS_TEMPORARY);
762  plugin = logical_slot ? NameStr(first_slot_contents.data.plugin) : NULL;
763 
764  /* Check type of replication slot */
765  if (src_islogical != logical_slot)
766  ereport(ERROR,
767  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
768  src_islogical ?
769  errmsg("cannot copy physical replication slot \"%s\" as a logical replication slot",
770  NameStr(*src_name)) :
771  errmsg("cannot copy logical replication slot \"%s\" as a physical replication slot",
772  NameStr(*src_name))));
773 
774  /* Copying non-reserved slot doesn't make sense */
775  if (XLogRecPtrIsInvalid(src_restart_lsn))
776  ereport(ERROR,
777  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
778  errmsg("cannot copy a replication slot that doesn't reserve WAL")));
779 
780  /* Overwrite params from optional arguments */
781  if (PG_NARGS() >= 3)
782  temporary = PG_GETARG_BOOL(2);
783  if (PG_NARGS() >= 4)
784  {
785  Assert(logical_slot);
786  plugin = NameStr(*(PG_GETARG_NAME(3)));
787  }
788 
789  /* Create new slot and acquire it */
790  if (logical_slot)
791  {
792  /*
793  * We must not try to read WAL, since we haven't reserved it yet --
794  * hence pass find_startpoint false. confirmed_flush will be set
795  * below, by copying from the source slot.
796  */
798  plugin,
799  temporary,
800  src_restart_lsn,
801  false);
802  }
803  else
805  true,
806  temporary,
807  src_restart_lsn);
808 
809  /*
810  * Update the destination slot to current values of the source slot;
811  * recheck that the source slot is still the one we saw previously.
812  */
813  {
814  TransactionId copy_effective_xmin;
815  TransactionId copy_effective_catalog_xmin;
816  TransactionId copy_xmin;
817  TransactionId copy_catalog_xmin;
818  XLogRecPtr copy_restart_lsn;
819  XLogRecPtr copy_confirmed_flush;
820  bool copy_islogical;
821  char *copy_name;
822 
823  /* Copy data of source slot again */
824  SpinLockAcquire(&src->mutex);
825  second_slot_contents = *src;
826  SpinLockRelease(&src->mutex);
827 
828  copy_effective_xmin = second_slot_contents.effective_xmin;
829  copy_effective_catalog_xmin = second_slot_contents.effective_catalog_xmin;
830 
831  copy_xmin = second_slot_contents.data.xmin;
832  copy_catalog_xmin = second_slot_contents.data.catalog_xmin;
833  copy_restart_lsn = second_slot_contents.data.restart_lsn;
834  copy_confirmed_flush = second_slot_contents.data.confirmed_flush;
835 
836  /* for existence check */
837  copy_name = NameStr(second_slot_contents.data.name);
838  copy_islogical = SlotIsLogical(&second_slot_contents);
839 
840  /*
841  * Check if the source slot still exists and is valid. We regard it as
842  * invalid if the type of replication slot or name has been changed,
843  * or the restart_lsn either is invalid or has gone backward. (The
844  * restart_lsn could go backwards if the source slot is dropped and
845  * copied from an older slot during installation.)
846  *
847  * Since erroring out will release and drop the destination slot we
848  * don't need to release it here.
849  */
850  if (copy_restart_lsn < src_restart_lsn ||
851  src_islogical != copy_islogical ||
852  strcmp(copy_name, NameStr(*src_name)) != 0)
853  ereport(ERROR,
854  (errmsg("could not copy replication slot \"%s\"",
855  NameStr(*src_name)),
856  errdetail("The source replication slot was modified incompatibly during the copy operation.")));
857 
858  /* The source slot must have a consistent snapshot */
859  if (src_islogical && XLogRecPtrIsInvalid(copy_confirmed_flush))
860  ereport(ERROR,
861  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
862  errmsg("cannot copy unfinished logical replication slot \"%s\"",
863  NameStr(*src_name)),
864  errhint("Retry when the source replication slot's confirmed_flush_lsn is valid.")));
865 
866  /* Install copied values again */
868  MyReplicationSlot->effective_xmin = copy_effective_xmin;
869  MyReplicationSlot->effective_catalog_xmin = copy_effective_catalog_xmin;
870 
871  MyReplicationSlot->data.xmin = copy_xmin;
872  MyReplicationSlot->data.catalog_xmin = copy_catalog_xmin;
873  MyReplicationSlot->data.restart_lsn = copy_restart_lsn;
874  MyReplicationSlot->data.confirmed_flush = copy_confirmed_flush;
876 
881 
882 #ifdef USE_ASSERT_CHECKING
883  /* Check that the restart_lsn is available */
884  {
885  XLogSegNo segno;
886 
887  XLByteToSeg(copy_restart_lsn, segno, wal_segment_size);
888  Assert(XLogGetLastRemovedSegno() < segno);
889  }
890 #endif
891  }
892 
893  /* target slot fully created, mark as persistent if needed */
894  if (logical_slot && !temporary)
896 
897  /* All done. Set up the return values */
898  values[0] = NameGetDatum(dst_name);
899  nulls[0] = false;
901  {
903  nulls[1] = false;
904  }
905  else
906  nulls[1] = true;
907 
908  tuple = heap_form_tuple(tupdesc, values, nulls);
909  result = HeapTupleGetDatum(tuple);
910 
912 
913  PG_RETURN_DATUM(result);
914 }
static void create_logical_replication_slot(char *name, char *plugin, bool temporary, XLogRecPtr restart_lsn, bool find_startpoint)
Definition: slotfuncs.c:126
static const char * plugin
ReplicationSlotCtlData * ReplicationSlotCtl
Definition: slot.c:93
void CheckSlotRequirements(void)
Definition: slot.c:1053
#define NameGetDatum(X)
Definition: postgres.h:595
TypeFuncClass get_call_result_type(FunctionCallInfo fcinfo, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition: funcapi.c:205
int errhint(const char *fmt,...)
Definition: elog.c:1068
static void create_physical_replication_slot(char *name, bool immediately_reserve, bool temporary, XLogRecPtr restart_lsn)
Definition: slotfuncs.c:46
int wal_segment_size
Definition: xlog.c:117
uint32 TransactionId
Definition: c.h:521
ReplicationSlotPersistency persistency
Definition: slot.h:61
int errcode(int sqlerrcode)
Definition: elog.c:610
#define LSNGetDatum(X)
Definition: pg_lsn.h:22
void ReplicationSlotSave(void)
Definition: slot.c:719
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
#define PG_GETARG_BOOL(n)
Definition: fmgr.h:274
ReplicationSlotPersistentData data
Definition: slot.h:143
XLogRecPtr confirmed_flush
Definition: slot.h:91
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1812
#define SpinLockAcquire(lock)
Definition: spin.h:62
XLogSegNo XLogGetLastRemovedSegno(void)
Definition: xlog.c:3959
void ReplicationSlotsComputeRequiredLSN(void)
Definition: slot.c:826
#define ERROR
Definition: elog.h:43
void ReplicationSlotPersist(void)
Definition: slot.c:754
TransactionId effective_xmin
Definition: slot.h:139
Definition: c.h:617
uint64 XLogSegNo
Definition: xlogdefs.h:41
int errdetail(const char *fmt,...)
Definition: elog.c:954
TransactionId catalog_xmin
Definition: slot.h:77
void ReplicationSlotRelease(void)
Definition: slot.c:484
TransactionId xmin
Definition: slot.h:69
#define SlotIsLogical(slot)
Definition: slot.h:165
static void check_permissions(void)
Definition: slotfuncs.c:29
#define XLogRecPtrIsInvalid(r)
Definition: xlogdefs.h:29
bool in_use
Definition: slot.h:119
#define SpinLockRelease(lock)
Definition: spin.h:64
uintptr_t Datum
Definition: postgres.h:367
#define PG_RETURN_DATUM(x)
Definition: fmgr.h:352
TransactionId effective_catalog_xmin
Definition: slot.h:140
#define ereport(elevel,...)
Definition: elog.h:144
ReplicationSlot * MyReplicationSlot
Definition: slot.c:96
int max_replication_slots
Definition: slot.c:99
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define Assert(condition)
Definition: c.h:746
XLogRecPtr restart_lsn
Definition: slot.h:80
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1208
#define PG_NARGS()
Definition: fmgr.h:203
#define HeapTupleGetDatum(tuple)
Definition: funcapi.h:221
static Datum values[MAXATTR]
Definition: bootstrap.c:165
int errmsg(const char *fmt,...)
Definition: elog.c:821
#define elog(elevel,...)
Definition: elog.h:214
int i
#define NameStr(name)
Definition: c.h:623
ReplicationSlot replication_slots[1]
Definition: slot.h:176
slock_t mutex
Definition: slot.h:116
void CheckLogicalDecodingRequirements(void)
Definition: logical.c:94
void ReplicationSlotsComputeRequiredXmin(bool already_locked)
Definition: slot.c:776
void ReplicationSlotMarkDirty(void)
Definition: slot.c:737
#define PG_GETARG_NAME(n)
Definition: fmgr.h:278
#define XLByteToSeg(xlrp, logSegNo, wal_segsz_bytes)

◆ create_logical_replication_slot()

static void create_logical_replication_slot ( char *  name,
char *  plugin,
bool  temporary,
XLogRecPtr  restart_lsn,
bool  find_startpoint 
)
static

Definition at line 126 of file slotfuncs.c.

References Assert, CreateInitDecodingContext(), DecodingContextFindStartpoint(), FreeDecodingContext(), MyReplicationSlot, NIL, read_local_xlog_page(), ReplicationSlotCreate(), RS_EPHEMERAL, RS_TEMPORARY, wal_segment_close(), wal_segment_open(), and XL_ROUTINE.

Referenced by copy_replication_slot(), and pg_create_logical_replication_slot().

129 {
130  LogicalDecodingContext *ctx = NULL;
131 
133 
134  /*
135  * Acquire a logical decoding slot, this will check for conflicting names.
136  * Initially create persistent slot as ephemeral - that allows us to
137  * nicely handle errors during initialization because it'll get dropped if
138  * this transaction fails. We'll make it persistent at the end. Temporary
139  * slots can be created as temporary from beginning as they get dropped on
140  * error as well.
141  */
143  temporary ? RS_TEMPORARY : RS_EPHEMERAL);
144 
145  /*
146  * Create logical decoding context to find start point or, if we don't
147  * need it, to 1) bump slot's restart_lsn and xmin 2) check plugin sanity.
148  *
149  * Note: when !find_startpoint this is still important, because it's at
150  * this point that the output plugin is validated.
151  */
153  false, /* just catalogs is OK */
154  restart_lsn,
155  XL_ROUTINE(.page_read = read_local_xlog_page,
156  .segment_open = wal_segment_open,
157  .segment_close = wal_segment_close),
158  NULL, NULL, NULL);
159 
160  /*
161  * If caller needs us to determine the decoding start point, do so now.
162  * This might take a while.
163  */
164  if (find_startpoint)
166 
167  /* don't need the decoding context anymore */
168  FreeDecodingContext(ctx);
169 }
#define NIL
Definition: pg_list.h:65
static const char * plugin
void wal_segment_close(XLogReaderState *state)
Definition: xlogutils.c:812
void ReplicationSlotCreate(const char *name, bool db_specific, ReplicationSlotPersistency persistency)
Definition: slot.c:221
void wal_segment_open(XLogReaderState *state, XLogSegNo nextSegNo, TimeLineID *tli_p)
Definition: xlogutils.c:787
void DecodingContextFindStartpoint(LogicalDecodingContext *ctx)
Definition: logical.c:527
#define XL_ROUTINE(...)
Definition: xlogreader.h:116
ReplicationSlot * MyReplicationSlot
Definition: slot.c:96
#define Assert(condition)
Definition: c.h:746
void FreeDecodingContext(LogicalDecodingContext *ctx)
Definition: logical.c:570
const char * name
Definition: encode.c:561
int read_local_xlog_page(XLogReaderState *state, XLogRecPtr targetPagePtr, int reqLen, XLogRecPtr targetRecPtr, char *cur_page)
Definition: xlogutils.c:831
LogicalDecodingContext * CreateInitDecodingContext(const char *plugin, List *output_plugin_options, bool need_full_snapshot, XLogRecPtr restart_lsn, XLogReaderRoutine *xl_routine, LogicalOutputPluginWriterPrepareWrite prepare_write, LogicalOutputPluginWriterWrite do_write, LogicalOutputPluginWriterUpdateProgress update_progress)
Definition: logical.c:283

◆ create_physical_replication_slot()

static void create_physical_replication_slot ( char *  name,
bool  immediately_reserve,
bool  temporary,
XLogRecPtr  restart_lsn 
)
static

Definition at line 46 of file slotfuncs.c.

References Assert, ReplicationSlot::data, MyReplicationSlot, ReplicationSlotCreate(), ReplicationSlotMarkDirty(), ReplicationSlotReserveWal(), ReplicationSlotSave(), ReplicationSlotPersistentData::restart_lsn, RS_PERSISTENT, RS_TEMPORARY, and XLogRecPtrIsInvalid.

Referenced by copy_replication_slot(), and pg_create_physical_replication_slot().

48 {
50 
51  /* acquire replication slot, this will check for conflicting names */
53  temporary ? RS_TEMPORARY : RS_PERSISTENT);
54 
55  if (immediately_reserve)
56  {
57  /* Reserve WAL as the user asked for it */
58  if (XLogRecPtrIsInvalid(restart_lsn))
60  else
61  MyReplicationSlot->data.restart_lsn = restart_lsn;
62 
63  /* Write this slot to disk */
66  }
67 }
void ReplicationSlotCreate(const char *name, bool db_specific, ReplicationSlotPersistency persistency)
Definition: slot.c:221
void ReplicationSlotSave(void)
Definition: slot.c:719
ReplicationSlotPersistentData data
Definition: slot.h:143
void ReplicationSlotReserveWal(void)
Definition: slot.c:1078
#define XLogRecPtrIsInvalid(r)
Definition: xlogdefs.h:29
ReplicationSlot * MyReplicationSlot
Definition: slot.c:96
#define Assert(condition)
Definition: c.h:746
XLogRecPtr restart_lsn
Definition: slot.h:80
const char * name
Definition: encode.c:561
void ReplicationSlotMarkDirty(void)
Definition: slot.c:737

◆ pg_copy_logical_replication_slot_a()

Datum pg_copy_logical_replication_slot_a ( PG_FUNCTION_ARGS  )

Definition at line 918 of file slotfuncs.c.

References copy_replication_slot().

919 {
920  return copy_replication_slot(fcinfo, true);
921 }
static Datum copy_replication_slot(FunctionCallInfo fcinfo, bool logical_slot)
Definition: slotfuncs.c:697

◆ pg_copy_logical_replication_slot_b()

Datum pg_copy_logical_replication_slot_b ( PG_FUNCTION_ARGS  )

Definition at line 924 of file slotfuncs.c.

References copy_replication_slot().

925 {
926  return copy_replication_slot(fcinfo, true);
927 }
static Datum copy_replication_slot(FunctionCallInfo fcinfo, bool logical_slot)
Definition: slotfuncs.c:697

◆ pg_copy_logical_replication_slot_c()

Datum pg_copy_logical_replication_slot_c ( PG_FUNCTION_ARGS  )

Definition at line 930 of file slotfuncs.c.

References copy_replication_slot().

931 {
932  return copy_replication_slot(fcinfo, true);
933 }
static Datum copy_replication_slot(FunctionCallInfo fcinfo, bool logical_slot)
Definition: slotfuncs.c:697

◆ pg_copy_physical_replication_slot_a()

Datum pg_copy_physical_replication_slot_a ( PG_FUNCTION_ARGS  )

Definition at line 936 of file slotfuncs.c.

References copy_replication_slot().

937 {
938  return copy_replication_slot(fcinfo, false);
939 }
static Datum copy_replication_slot(FunctionCallInfo fcinfo, bool logical_slot)
Definition: slotfuncs.c:697

◆ pg_copy_physical_replication_slot_b()

Datum pg_copy_physical_replication_slot_b ( PG_FUNCTION_ARGS  )

Definition at line 942 of file slotfuncs.c.

References copy_replication_slot().

943 {
944  return copy_replication_slot(fcinfo, false);
945 }
static Datum copy_replication_slot(FunctionCallInfo fcinfo, bool logical_slot)
Definition: slotfuncs.c:697

◆ pg_create_logical_replication_slot()

Datum pg_create_logical_replication_slot ( PG_FUNCTION_ARGS  )

Definition at line 175 of file slotfuncs.c.

References check_permissions(), CheckLogicalDecodingRequirements(), ReplicationSlotPersistentData::confirmed_flush, create_logical_replication_slot(), ReplicationSlot::data, elog, ERROR, get_call_result_type(), heap_form_tuple(), HeapTupleGetDatum, InvalidXLogRecPtr, LSNGetDatum, MyReplicationSlot, ReplicationSlotPersistentData::name, name, NameGetDatum, NameStr, PG_GETARG_BOOL, PG_GETARG_NAME, PG_RETURN_DATUM, plugin, ReplicationSlotPersist(), ReplicationSlotRelease(), TYPEFUNC_COMPOSITE, and values.

176 {
177  Name name = PG_GETARG_NAME(0);
179  bool temporary = PG_GETARG_BOOL(2);
180  Datum result;
181  TupleDesc tupdesc;
182  HeapTuple tuple;
183  Datum values[2];
184  bool nulls[2];
185 
186  if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
187  elog(ERROR, "return type must be a row type");
188 
190 
192 
194  NameStr(*plugin),
195  temporary,
197  true);
198 
199  values[0] = NameGetDatum(&MyReplicationSlot->data.name);
201 
202  memset(nulls, 0, sizeof(nulls));
203 
204  tuple = heap_form_tuple(tupdesc, values, nulls);
205  result = HeapTupleGetDatum(tuple);
206 
207  /* ok, slot is now fully created, mark it as persistent if needed */
208  if (!temporary)
211 
212  PG_RETURN_DATUM(result);
213 }
static void create_logical_replication_slot(char *name, char *plugin, bool temporary, XLogRecPtr restart_lsn, bool find_startpoint)
Definition: slotfuncs.c:126
static const char * plugin
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
#define NameGetDatum(X)
Definition: postgres.h:595
TypeFuncClass get_call_result_type(FunctionCallInfo fcinfo, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition: funcapi.c:205
#define LSNGetDatum(X)
Definition: pg_lsn.h:22
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
#define PG_GETARG_BOOL(n)
Definition: fmgr.h:274
ReplicationSlotPersistentData data
Definition: slot.h:143
XLogRecPtr confirmed_flush
Definition: slot.h:91
#define ERROR
Definition: elog.h:43
void ReplicationSlotPersist(void)
Definition: slot.c:754
Definition: c.h:617
void ReplicationSlotRelease(void)
Definition: slot.c:484
static void check_permissions(void)
Definition: slotfuncs.c:29
uintptr_t Datum
Definition: postgres.h:367
#define PG_RETURN_DATUM(x)
Definition: fmgr.h:352
ReplicationSlot * MyReplicationSlot
Definition: slot.c:96
#define HeapTupleGetDatum(tuple)
Definition: funcapi.h:221
const char * name
Definition: encode.c:561
static Datum values[MAXATTR]
Definition: bootstrap.c:165
#define elog(elevel,...)
Definition: elog.h:214
#define NameStr(name)
Definition: c.h:623
void CheckLogicalDecodingRequirements(void)
Definition: logical.c:94
#define PG_GETARG_NAME(n)
Definition: fmgr.h:278

◆ pg_create_physical_replication_slot()

Datum pg_create_physical_replication_slot ( PG_FUNCTION_ARGS  )

Definition at line 74 of file slotfuncs.c.

References check_permissions(), CheckSlotRequirements(), create_physical_replication_slot(), ReplicationSlot::data, elog, ERROR, get_call_result_type(), heap_form_tuple(), HeapTupleGetDatum, InvalidXLogRecPtr, LSNGetDatum, MyReplicationSlot, ReplicationSlotPersistentData::name, name, NameGetDatum, NameStr, PG_GETARG_BOOL, PG_GETARG_NAME, PG_RETURN_DATUM, ReplicationSlotRelease(), ReplicationSlotPersistentData::restart_lsn, TYPEFUNC_COMPOSITE, and values.

75 {
77  bool immediately_reserve = PG_GETARG_BOOL(1);
78  bool temporary = PG_GETARG_BOOL(2);
79  Datum values[2];
80  bool nulls[2];
81  TupleDesc tupdesc;
82  HeapTuple tuple;
83  Datum result;
84 
85  if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
86  elog(ERROR, "return type must be a row type");
87 
89 
91 
93  immediately_reserve,
94  temporary,
96 
97  values[0] = NameGetDatum(&MyReplicationSlot->data.name);
98  nulls[0] = false;
99 
100  if (immediately_reserve)
101  {
103  nulls[1] = false;
104  }
105  else
106  nulls[1] = true;
107 
108  tuple = heap_form_tuple(tupdesc, values, nulls);
109  result = HeapTupleGetDatum(tuple);
110 
112 
113  PG_RETURN_DATUM(result);
114 }
void CheckSlotRequirements(void)
Definition: slot.c:1053
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
#define NameGetDatum(X)
Definition: postgres.h:595
TypeFuncClass get_call_result_type(FunctionCallInfo fcinfo, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition: funcapi.c:205
static void create_physical_replication_slot(char *name, bool immediately_reserve, bool temporary, XLogRecPtr restart_lsn)
Definition: slotfuncs.c:46
#define LSNGetDatum(X)
Definition: pg_lsn.h:22
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
#define PG_GETARG_BOOL(n)
Definition: fmgr.h:274
ReplicationSlotPersistentData data
Definition: slot.h:143
#define ERROR
Definition: elog.h:43
Definition: c.h:617
void ReplicationSlotRelease(void)
Definition: slot.c:484
static void check_permissions(void)
Definition: slotfuncs.c:29
uintptr_t Datum
Definition: postgres.h:367
#define PG_RETURN_DATUM(x)
Definition: fmgr.h:352
ReplicationSlot * MyReplicationSlot
Definition: slot.c:96
XLogRecPtr restart_lsn
Definition: slot.h:80
#define HeapTupleGetDatum(tuple)
Definition: funcapi.h:221
const char * name
Definition: encode.c:561
static Datum values[MAXATTR]
Definition: bootstrap.c:165
#define elog(elevel,...)
Definition: elog.h:214
#define NameStr(name)
Definition: c.h:623
#define PG_GETARG_NAME(n)
Definition: fmgr.h:278

◆ pg_drop_replication_slot()

Datum pg_drop_replication_slot ( PG_FUNCTION_ARGS  )

Definition at line 220 of file slotfuncs.c.

References check_permissions(), CheckSlotRequirements(), name, NameStr, PG_GETARG_NAME, PG_RETURN_VOID, and ReplicationSlotDrop().

221 {
222  Name name = PG_GETARG_NAME(0);
223 
225 
227 
228  ReplicationSlotDrop(NameStr(*name), true);
229 
230  PG_RETURN_VOID();
231 }
void CheckSlotRequirements(void)
Definition: slot.c:1053
Definition: c.h:617
static void check_permissions(void)
Definition: slotfuncs.c:29
#define PG_RETURN_VOID()
Definition: fmgr.h:348
const char * name
Definition: encode.c:561
void ReplicationSlotDrop(const char *name, bool nowait)
Definition: slot.c:578
#define NameStr(name)
Definition: c.h:623
#define PG_GETARG_NAME(n)
Definition: fmgr.h:278

◆ pg_get_replication_slots()

Datum pg_get_replication_slots ( PG_FUNCTION_ARGS  )

Definition at line 237 of file slotfuncs.c.

References ReplicationSlot::active_pid, ReturnSetInfo::allowedModes, Assert, BoolGetDatum, ReplicationSlotPersistentData::catalog_xmin, ReplicationSlotPersistentData::confirmed_flush, CStringGetTextDatum, ReplicationSlot::data, ReplicationSlotPersistentData::database, ReturnSetInfo::econtext, ExprContext::ecxt_per_query_memory, elog, ereport, errcode(), errmsg(), ERROR, get_call_result_type(), GetWALAvailability(), GetXLogWriteRecPtr(), i, ReplicationSlot::in_use, Int32GetDatum, Int64GetDatum(), ReplicationSlotPersistentData::invalidated_at, InvalidOid, InvalidTransactionId, InvalidXLogRecPtr, IsA, LSNGetDatum, LW_SHARED, LWLockAcquire(), LWLockRelease(), Max, max_replication_slots, max_slot_wal_keep_size_mb, MemoryContextSwitchTo(), ReplicationSlot::mutex, ReplicationSlotPersistentData::name, NameGetDatum, ObjectIdGetDatum, ReplicationSlotPersistentData::persistency, PG_GET_REPLICATION_SLOTS_COLS, ReplicationSlotPersistentData::plugin, ReplicationSlotCtlData::replication_slots, ReplicationSlotCtl, ReplicationSlotPersistentData::restart_lsn, ReturnSetInfo::returnMode, RS_TEMPORARY, ReturnSetInfo::setDesc, ReturnSetInfo::setResult, SFRM_Materialize, SpinLockAcquire, SpinLockRelease, TransactionIdGetDatum, tuplestore_begin_heap(), tuplestore_donestoring, tuplestore_putvalues(), TYPEFUNC_COMPOSITE, values, wal_keep_size_mb, wal_segment_size, WALAVAIL_EXTENDED, WALAVAIL_INVALID_LSN, WALAVAIL_REMOVED, WALAVAIL_RESERVED, WALAVAIL_UNRESERVED, work_mem, XLByteToSeg, XLogMBVarToSegs, XLogRecPtrIsInvalid, XLogSegNoOffsetToRecPtr, and ReplicationSlotPersistentData::xmin.

238 {
239 #define PG_GET_REPLICATION_SLOTS_COLS 13
240  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
241  TupleDesc tupdesc;
242  Tuplestorestate *tupstore;
243  MemoryContext per_query_ctx;
244  MemoryContext oldcontext;
245  XLogRecPtr currlsn;
246  int slotno;
247 
248  /* check to see if caller supports us returning a tuplestore */
249  if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
250  ereport(ERROR,
251  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
252  errmsg("set-valued function called in context that cannot accept a set")));
253  if (!(rsinfo->allowedModes & SFRM_Materialize))
254  ereport(ERROR,
255  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
256  errmsg("materialize mode required, but it is not allowed in this context")));
257 
258  /* Build a tuple descriptor for our result type */
259  if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
260  elog(ERROR, "return type must be a row type");
261 
262  /*
263  * We don't require any special permission to see this function's data
264  * because nothing should be sensitive. The most critical being the slot
265  * name, which shouldn't contain anything particularly sensitive.
266  */
267 
268  per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
269  oldcontext = MemoryContextSwitchTo(per_query_ctx);
270 
271  tupstore = tuplestore_begin_heap(true, false, work_mem);
272  rsinfo->returnMode = SFRM_Materialize;
273  rsinfo->setResult = tupstore;
274  rsinfo->setDesc = tupdesc;
275 
276  MemoryContextSwitchTo(oldcontext);
277 
278  currlsn = GetXLogWriteRecPtr();
279 
280  LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
281  for (slotno = 0; slotno < max_replication_slots; slotno++)
282  {
284  ReplicationSlot slot_contents;
286  bool nulls[PG_GET_REPLICATION_SLOTS_COLS];
287  WALAvailability walstate;
288  int i;
289 
290  if (!slot->in_use)
291  continue;
292 
293  /* Copy slot contents while holding spinlock, then examine at leisure */
294  SpinLockAcquire(&slot->mutex);
295  slot_contents = *slot;
296  SpinLockRelease(&slot->mutex);
297 
298  memset(values, 0, sizeof(values));
299  memset(nulls, 0, sizeof(nulls));
300 
301  i = 0;
302  values[i++] = NameGetDatum(&slot_contents.data.name);
303 
304  if (slot_contents.data.database == InvalidOid)
305  nulls[i++] = true;
306  else
307  values[i++] = NameGetDatum(&slot_contents.data.plugin);
308 
309  if (slot_contents.data.database == InvalidOid)
310  values[i++] = CStringGetTextDatum("physical");
311  else
312  values[i++] = CStringGetTextDatum("logical");
313 
314  if (slot_contents.data.database == InvalidOid)
315  nulls[i++] = true;
316  else
317  values[i++] = ObjectIdGetDatum(slot_contents.data.database);
318 
319  values[i++] = BoolGetDatum(slot_contents.data.persistency == RS_TEMPORARY);
320  values[i++] = BoolGetDatum(slot_contents.active_pid != 0);
321 
322  if (slot_contents.active_pid != 0)
323  values[i++] = Int32GetDatum(slot_contents.active_pid);
324  else
325  nulls[i++] = true;
326 
327  if (slot_contents.data.xmin != InvalidTransactionId)
328  values[i++] = TransactionIdGetDatum(slot_contents.data.xmin);
329  else
330  nulls[i++] = true;
331 
332  if (slot_contents.data.catalog_xmin != InvalidTransactionId)
333  values[i++] = TransactionIdGetDatum(slot_contents.data.catalog_xmin);
334  else
335  nulls[i++] = true;
336 
337  if (slot_contents.data.restart_lsn != InvalidXLogRecPtr)
338  values[i++] = LSNGetDatum(slot_contents.data.restart_lsn);
339  else
340  nulls[i++] = true;
341 
342  if (slot_contents.data.confirmed_flush != InvalidXLogRecPtr)
343  values[i++] = LSNGetDatum(slot_contents.data.confirmed_flush);
344  else
345  nulls[i++] = true;
346 
347  /*
348  * If invalidated_at is valid and restart_lsn is invalid, we know for
349  * certain that the slot has been invalidated. Otherwise, test
350  * availability from restart_lsn.
351  */
352  if (XLogRecPtrIsInvalid(slot_contents.data.restart_lsn) &&
353  !XLogRecPtrIsInvalid(slot_contents.data.invalidated_at))
354  walstate = WALAVAIL_REMOVED;
355  else
356  walstate = GetWALAvailability(slot_contents.data.restart_lsn);
357 
358  switch (walstate)
359  {
361  nulls[i++] = true;
362  break;
363 
364  case WALAVAIL_RESERVED:
365  values[i++] = CStringGetTextDatum("reserved");
366  break;
367 
368  case WALAVAIL_EXTENDED:
369  values[i++] = CStringGetTextDatum("extended");
370  break;
371 
372  case WALAVAIL_UNRESERVED:
373  values[i++] = CStringGetTextDatum("unreserved");
374  break;
375 
376  case WALAVAIL_REMOVED:
377 
378  /*
379  * If we read the restart_lsn long enough ago, maybe that file
380  * has been removed by now. However, the walsender could have
381  * moved forward enough that it jumped to another file after
382  * we looked. If checkpointer signalled the process to
383  * termination, then it's definitely lost; but if a process is
384  * still alive, then "unreserved" seems more appropriate.
385  *
386  * If we do change it, save the state for safe_wal_size below.
387  */
388  if (!XLogRecPtrIsInvalid(slot_contents.data.restart_lsn))
389  {
390  int pid;
391 
392  SpinLockAcquire(&slot->mutex);
393  pid = slot->active_pid;
394  slot_contents.data.restart_lsn = slot->data.restart_lsn;
395  SpinLockRelease(&slot->mutex);
396  if (pid != 0)
397  {
398  values[i++] = CStringGetTextDatum("unreserved");
399  walstate = WALAVAIL_UNRESERVED;
400  break;
401  }
402  }
403  values[i++] = CStringGetTextDatum("lost");
404  break;
405  }
406 
407  /*
408  * safe_wal_size is only computed for slots that have not been lost,
409  * and only if there's a configured maximum size.
410  */
411  if (walstate == WALAVAIL_REMOVED || max_slot_wal_keep_size_mb < 0)
412  nulls[i++] = true;
413  else
414  {
415  XLogSegNo targetSeg;
416  uint64 slotKeepSegs;
417  uint64 keepSegs;
418  XLogSegNo failSeg;
419  XLogRecPtr failLSN;
420 
421  XLByteToSeg(slot_contents.data.restart_lsn, targetSeg, wal_segment_size);
422 
423  /* determine how many segments slots can be kept by slots */
425  /* ditto for wal_keep_size */
427 
428  /* if currpos reaches failLSN, we lose our segment */
429  failSeg = targetSeg + Max(slotKeepSegs, keepSegs) + 1;
430  XLogSegNoOffsetToRecPtr(failSeg, 0, wal_segment_size, failLSN);
431 
432  values[i++] = Int64GetDatum(failLSN - currlsn);
433  }
434 
436 
437  tuplestore_putvalues(tupstore, tupdesc, values, nulls);
438  }
439 
440  LWLockRelease(ReplicationSlotControlLock);
441 
442  tuplestore_donestoring(tupstore);
443 
444  return (Datum) 0;
445 }
void tuplestore_putvalues(Tuplestorestate *state, TupleDesc tdesc, Datum *values, bool *isnull)
Definition: tuplestore.c:750
ReplicationSlotCtlData * ReplicationSlotCtl
Definition: slot.c:93
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
#define IsA(nodeptr, _type_)
Definition: nodes.h:579
#define NameGetDatum(X)
Definition: postgres.h:595
TypeFuncClass get_call_result_type(FunctionCallInfo fcinfo, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition: funcapi.c:205
int wal_segment_size
Definition: xlog.c:117
#define PG_GET_REPLICATION_SLOTS_COLS
WALAvailability
Definition: xlog.h:271
#define tuplestore_donestoring(state)
Definition: tuplestore.h:60
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
ReplicationSlotPersistency persistency
Definition: slot.h:61
int errcode(int sqlerrcode)
Definition: elog.c:610
#define LSNGetDatum(X)
Definition: pg_lsn.h:22
int wal_keep_size_mb
Definition: xlog.c:92
ReplicationSlotPersistentData data
Definition: slot.h:143
XLogRecPtr confirmed_flush
Definition: slot.h:91
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1812
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
uint64 XLogSegNo
Definition: xlogdefs.h:41
TransactionId catalog_xmin
Definition: slot.h:77
#define InvalidTransactionId
Definition: transam.h:31
TransactionId xmin
Definition: slot.h:69
Datum Int64GetDatum(int64 X)
Definition: fmgr.c:1701
#define XLogRecPtrIsInvalid(r)
Definition: xlogdefs.h:29
bool in_use
Definition: slot.h:119
#define SpinLockRelease(lock)
Definition: spin.h:64
Tuplestorestate * tuplestore_begin_heap(bool randomAccess, bool interXact, int maxKBytes)
Definition: tuplestore.c:318
#define TransactionIdGetDatum(X)
Definition: postgres.h:521
uintptr_t Datum
Definition: postgres.h:367
int work_mem
Definition: globals.c:121
#define BoolGetDatum(X)
Definition: postgres.h:402
#define InvalidOid
Definition: postgres_ext.h:36
#define XLogMBVarToSegs(mbvar, wal_segsz_bytes)
#define ereport(elevel,...)
Definition: elog.h:144
int allowedModes
Definition: execnodes.h:304
int max_slot_wal_keep_size_mb
Definition: xlog.c:111
XLogRecPtr GetXLogWriteRecPtr(void)
Definition: xlog.c:11535
SetFunctionReturnMode returnMode
Definition: execnodes.h:306
#define Max(x, y)
Definition: c.h:922
int max_replication_slots
Definition: slot.c:99
#define XLogSegNoOffsetToRecPtr(segno, offset, wal_segsz_bytes, dest)
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define Assert(condition)
Definition: c.h:746
XLogRecPtr restart_lsn
Definition: slot.h:80
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1208
MemoryContext ecxt_per_query_memory
Definition: execnodes.h:232
Tuplestorestate * setResult
Definition: execnodes.h:309
static Datum values[MAXATTR]
Definition: bootstrap.c:165
ExprContext * econtext
Definition: execnodes.h:302
#define Int32GetDatum(X)
Definition: postgres.h:479
TupleDesc setDesc
Definition: execnodes.h:310
int errmsg(const char *fmt,...)
Definition: elog.c:821
pid_t active_pid
Definition: slot.h:122
WALAvailability GetWALAvailability(XLogRecPtr targetLSN)
Definition: xlog.c:9522
#define elog(elevel,...)
Definition: elog.h:214
int i
#define CStringGetTextDatum(s)
Definition: builtins.h:86
ReplicationSlot replication_slots[1]
Definition: slot.h:176
XLogRecPtr invalidated_at
Definition: slot.h:83
slock_t mutex
Definition: slot.h:116
#define XLByteToSeg(xlrp, logSegNo, wal_segsz_bytes)

◆ pg_logical_replication_slot_advance()

static XLogRecPtr pg_logical_replication_slot_advance ( XLogRecPtr  moveto)
static

Definition at line 492 of file slotfuncs.c.

References Assert, CHECK_FOR_INTERRUPTS, ReplicationSlotPersistentData::confirmed_flush, CreateDecodingContext(), CurrentResourceOwner, ReplicationSlot::data, elog, XLogReaderState::EndRecPtr, ERROR, FreeDecodingContext(), InvalidateSystemCaches(), InvalidXLogRecPtr, LogicalConfirmReceivedLocation(), LogicalDecodingProcessRecord(), MyReplicationSlot, NIL, PG_CATCH, PG_END_TRY, PG_RE_THROW, PG_TRY, read_local_xlog_page(), LogicalDecodingContext::reader, ReplicationSlotMarkDirty(), ReplicationSlotPersistentData::restart_lsn, wal_segment_close(), wal_segment_open(), XL_ROUTINE, XLogBeginRead(), and XLogReadRecord().

Referenced by pg_replication_slot_advance().

493 {
495  ResourceOwner old_resowner = CurrentResourceOwner;
496  XLogRecPtr retlsn;
497 
498  Assert(moveto != InvalidXLogRecPtr);
499 
500  PG_TRY();
501  {
502  /*
503  * Create our decoding context in fast_forward mode, passing start_lsn
504  * as InvalidXLogRecPtr, so that we start processing from my slot's
505  * confirmed_flush.
506  */
508  NIL,
509  true, /* fast_forward */
510  XL_ROUTINE(.page_read = read_local_xlog_page,
511  .segment_open = wal_segment_open,
512  .segment_close = wal_segment_close),
513  NULL, NULL, NULL);
514 
515  /*
516  * Start reading at the slot's restart_lsn, which we know to point to
517  * a valid record.
518  */
520 
521  /* invalidate non-timetravel entries */
523 
524  /* Decode at least one record, until we run out of records */
525  while (ctx->reader->EndRecPtr < moveto)
526  {
527  char *errm = NULL;
528  XLogRecord *record;
529 
530  /*
531  * Read records. No changes are generated in fast_forward mode,
532  * but snapbuilder/slot statuses are updated properly.
533  */
534  record = XLogReadRecord(ctx->reader, &errm);
535  if (errm)
536  elog(ERROR, "%s", errm);
537 
538  /*
539  * Process the record. Storage-level changes are ignored in
540  * fast_forward mode, but other modules (such as snapbuilder)
541  * might still have critical updates to do.
542  */
543  if (record)
545 
546  /* Stop once the requested target has been reached */
547  if (moveto <= ctx->reader->EndRecPtr)
548  break;
549 
551  }
552 
553  /*
554  * Logical decoding could have clobbered CurrentResourceOwner during
555  * transaction management, so restore the executor's value. (This is
556  * a kluge, but it's not worth cleaning up right now.)
557  */
558  CurrentResourceOwner = old_resowner;
559 
560  if (ctx->reader->EndRecPtr != InvalidXLogRecPtr)
561  {
563 
564  /*
565  * If only the confirmed_flush LSN has changed the slot won't get
566  * marked as dirty by the above. Callers on the walsender
567  * interface are expected to keep track of their own progress and
568  * don't need it written out. But SQL-interface users cannot
569  * specify their own start positions and it's harder for them to
570  * keep track of their progress, so we should make more of an
571  * effort to save it for them.
572  *
573  * Dirty the slot so it is written out at the next checkpoint. The
574  * LSN position advanced to may still be lost on a crash but this
575  * makes the data consistent after a clean shutdown.
576  */
578  }
579 
581 
582  /* free context, call shutdown callback */
583  FreeDecodingContext(ctx);
584 
586  }
587  PG_CATCH();
588  {
589  /* clear all timetravel entries */
591 
592  PG_RE_THROW();
593  }
594  PG_END_TRY();
595 
596  return retlsn;
597 }
#define NIL
Definition: pg_list.h:65
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
void wal_segment_close(XLogReaderState *state)
Definition: xlogutils.c:812
ResourceOwner CurrentResourceOwner
Definition: resowner.c:142
void wal_segment_open(XLogReaderState *state, XLogSegNo nextSegNo, TimeLineID *tli_p)
Definition: xlogutils.c:787
ReplicationSlotPersistentData data
Definition: slot.h:143
void InvalidateSystemCaches(void)
Definition: inval.c:646
XLogRecPtr confirmed_flush
Definition: slot.h:91
XLogRecPtr EndRecPtr
Definition: xlogreader.h:176
XLogRecord * XLogReadRecord(XLogReaderState *state, char **errormsg)
Definition: xlogreader.c:268
#define ERROR
Definition: elog.h:43
void LogicalDecodingProcessRecord(LogicalDecodingContext *ctx, XLogReaderState *record)
Definition: decode.c:94
LogicalDecodingContext * CreateDecodingContext(XLogRecPtr start_lsn, List *output_plugin_options, bool fast_forward, XLogReaderRoutine *xl_routine, LogicalOutputPluginWriterPrepareWrite prepare_write, LogicalOutputPluginWriterWrite do_write, LogicalOutputPluginWriterUpdateProgress update_progress)
Definition: logical.c:435
void XLogBeginRead(XLogReaderState *state, XLogRecPtr RecPtr)
Definition: xlogreader.c:240
#define XL_ROUTINE(...)
Definition: xlogreader.h:116
#define PG_CATCH()
Definition: elog.h:305
ReplicationSlot * MyReplicationSlot
Definition: slot.c:96
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define Assert(condition)
Definition: c.h:746
void FreeDecodingContext(LogicalDecodingContext *ctx)
Definition: logical.c:570
XLogRecPtr restart_lsn
Definition: slot.h:80
#define PG_RE_THROW()
Definition: elog.h:336
void LogicalConfirmReceivedLocation(XLogRecPtr lsn)
Definition: logical.c:1372
XLogReaderState * reader
Definition: logical.h:41
#define elog(elevel,...)
Definition: elog.h:214
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
#define PG_TRY()
Definition: elog.h:295
int read_local_xlog_page(XLogReaderState *state, XLogRecPtr targetPagePtr, int reqLen, XLogRecPtr targetRecPtr, char *cur_page)
Definition: xlogutils.c:831
#define PG_END_TRY()
Definition: elog.h:320
void ReplicationSlotMarkDirty(void)
Definition: slot.c:737

◆ pg_physical_replication_slot_advance()

static XLogRecPtr pg_physical_replication_slot_advance ( XLogRecPtr  moveto)
static

Definition at line 455 of file slotfuncs.c.

References Assert, ReplicationSlot::data, InvalidXLogRecPtr, ReplicationSlot::mutex, MyReplicationSlot, ReplicationSlotMarkDirty(), ReplicationSlotPersistentData::restart_lsn, SpinLockAcquire, and SpinLockRelease.

Referenced by pg_replication_slot_advance().

456 {
458  XLogRecPtr retlsn = startlsn;
459 
460  Assert(moveto != InvalidXLogRecPtr);
461 
462  if (startlsn < moveto)
463  {
467  retlsn = moveto;
468 
469  /*
470  * Dirty the slot so as it is written out at the next checkpoint. Note
471  * that the LSN position advanced may still be lost in the event of a
472  * crash, but this makes the data consistent after a clean shutdown.
473  */
475  }
476 
477  return retlsn;
478 }
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
ReplicationSlotPersistentData data
Definition: slot.h:143
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define SpinLockRelease(lock)
Definition: spin.h:64
ReplicationSlot * MyReplicationSlot
Definition: slot.c:96
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define Assert(condition)
Definition: c.h:746
XLogRecPtr restart_lsn
Definition: slot.h:80
slock_t mutex
Definition: slot.h:116
void ReplicationSlotMarkDirty(void)
Definition: slot.c:737

◆ pg_replication_slot_advance()

Datum pg_replication_slot_advance ( PG_FUNCTION_ARGS  )

Definition at line 603 of file slotfuncs.c.

References Assert, check_permissions(), ReplicationSlotPersistentData::confirmed_flush, ReplicationSlot::data, ReplicationSlotPersistentData::database, elog, ereport, errcode(), errdetail(), errmsg(), ERROR, get_call_result_type(), GetFlushRecPtr(), GetXLogReplayRecPtr(), heap_form_tuple(), HeapTupleGetDatum, LSNGetDatum, Min, MyReplicationSlot, ReplicationSlotPersistentData::name, NameGetDatum, NameStr, OidIsValid, PG_GETARG_LSN, PG_GETARG_NAME, pg_logical_replication_slot_advance(), pg_physical_replication_slot_advance(), PG_RETURN_DATUM, RecoveryInProgress(), ReplicationSlotAcquire(), ReplicationSlotRelease(), ReplicationSlotsComputeRequiredLSN(), ReplicationSlotsComputeRequiredXmin(), ReplicationSlotPersistentData::restart_lsn, SAB_Error, ThisTimeLineID, TYPEFUNC_COMPOSITE, values, and XLogRecPtrIsInvalid.

604 {
605  Name slotname = PG_GETARG_NAME(0);
606  XLogRecPtr moveto = PG_GETARG_LSN(1);
607  XLogRecPtr endlsn;
608  XLogRecPtr minlsn;
609  TupleDesc tupdesc;
610  Datum values[2];
611  bool nulls[2];
612  HeapTuple tuple;
613  Datum result;
614 
616 
618 
619  if (XLogRecPtrIsInvalid(moveto))
620  ereport(ERROR,
621  (errmsg("invalid target WAL LSN")));
622 
623  /* Build a tuple descriptor for our result type */
624  if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
625  elog(ERROR, "return type must be a row type");
626 
627  /*
628  * We can't move slot past what's been flushed/replayed so clamp the
629  * target position accordingly.
630  */
631  if (!RecoveryInProgress())
632  moveto = Min(moveto, GetFlushRecPtr());
633  else
634  moveto = Min(moveto, GetXLogReplayRecPtr(&ThisTimeLineID));
635 
636  /* Acquire the slot so we "own" it */
637  (void) ReplicationSlotAcquire(NameStr(*slotname), SAB_Error);
638 
639  /* A slot whose restart_lsn has never been reserved cannot be advanced */
641  ereport(ERROR,
642  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
643  errmsg("replication slot \"%s\" cannot be advanced",
644  NameStr(*slotname)),
645  errdetail("This slot has never previously reserved WAL, or has been invalidated.")));
646 
647  /*
648  * Check if the slot is not moving backwards. Physical slots rely simply
649  * on restart_lsn as a minimum point, while logical slots have confirmed
650  * consumption up to confirmed_flush, meaning that in both cases data
651  * older than that is not available anymore.
652  */
655  else
657 
658  if (moveto < minlsn)
659  ereport(ERROR,
660  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
661  errmsg("cannot advance replication slot to %X/%X, minimum is %X/%X",
662  (uint32) (moveto >> 32), (uint32) moveto,
663  (uint32) (minlsn >> 32), (uint32) minlsn)));
664 
665  /* Do the actual slot update, depending on the slot type */
667  endlsn = pg_logical_replication_slot_advance(moveto);
668  else
669  endlsn = pg_physical_replication_slot_advance(moveto);
670 
671  values[0] = NameGetDatum(&MyReplicationSlot->data.name);
672  nulls[0] = false;
673 
674  /*
675  * Recompute the minimum LSN and xmin across all slots to adjust with the
676  * advancing potentially done.
677  */
680 
682 
683  /* Return the reached position. */
684  values[1] = LSNGetDatum(endlsn);
685  nulls[1] = false;
686 
687  tuple = heap_form_tuple(tupdesc, values, nulls);
688  result = HeapTupleGetDatum(tuple);
689 
690  PG_RETURN_DATUM(result);
691 }
static XLogRecPtr pg_logical_replication_slot_advance(XLogRecPtr moveto)
Definition: slotfuncs.c:492
#define NameGetDatum(X)
Definition: postgres.h:595
TypeFuncClass get_call_result_type(FunctionCallInfo fcinfo, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition: funcapi.c:205
#define Min(x, y)
Definition: c.h:928
int errcode(int sqlerrcode)
Definition: elog.c:610
#define LSNGetDatum(X)
Definition: pg_lsn.h:22
XLogRecPtr GetFlushRecPtr(void)
Definition: xlog.c:8428
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
ReplicationSlotPersistentData data
Definition: slot.h:143
bool RecoveryInProgress(void)
Definition: xlog.c:8076
#define OidIsValid(objectId)
Definition: c.h:652
XLogRecPtr confirmed_flush
Definition: slot.h:91
void ReplicationSlotsComputeRequiredLSN(void)
Definition: slot.c:826
#define ERROR
Definition: elog.h:43
XLogRecPtr GetXLogReplayRecPtr(TimeLineID *replayTLI)
Definition: xlog.c:11500
Definition: c.h:617
int errdetail(const char *fmt,...)
Definition: elog.c:954
unsigned int uint32
Definition: c.h:375
void ReplicationSlotRelease(void)
Definition: slot.c:484
static void check_permissions(void)
Definition: slotfuncs.c:29
#define XLogRecPtrIsInvalid(r)
Definition: xlogdefs.h:29
#define PG_GETARG_LSN(n)
Definition: pg_lsn.h:24
uintptr_t Datum
Definition: postgres.h:367
#define PG_RETURN_DATUM(x)
Definition: fmgr.h:352
TimeLineID ThisTimeLineID
Definition: xlog.c:192
#define ereport(elevel,...)
Definition: elog.h:144
ReplicationSlot * MyReplicationSlot
Definition: slot.c:96
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define Assert(condition)
Definition: c.h:746
XLogRecPtr restart_lsn
Definition: slot.h:80
#define HeapTupleGetDatum(tuple)
Definition: funcapi.h:221
static Datum values[MAXATTR]
Definition: bootstrap.c:165
int errmsg(const char *fmt,...)
Definition: elog.c:821
int ReplicationSlotAcquire(const char *name, SlotAcquireBehavior behavior)
Definition: slot.c:375
#define elog(elevel,...)
Definition: elog.h:214
Definition: slot.h:42
#define NameStr(name)
Definition: c.h:623
static XLogRecPtr pg_physical_replication_slot_advance(XLogRecPtr moveto)
Definition: slotfuncs.c:455
void ReplicationSlotsComputeRequiredXmin(bool already_locked)
Definition: slot.c:776
#define PG_GETARG_NAME(n)
Definition: fmgr.h:278