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:450
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:631
int errmsg(const char *fmt,...)
Definition: elog.c:824

◆ copy_replication_slot()

static Datum copy_replication_slot ( FunctionCallInfo  fcinfo,
bool  logical_slot 
)
static

Definition at line 700 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().

701 {
702  Name src_name = PG_GETARG_NAME(0);
703  Name dst_name = PG_GETARG_NAME(1);
704  ReplicationSlot *src = NULL;
705  ReplicationSlot first_slot_contents;
706  ReplicationSlot second_slot_contents;
707  XLogRecPtr src_restart_lsn;
708  bool src_islogical;
709  bool temporary;
710  char *plugin;
711  Datum values[2];
712  bool nulls[2];
713  Datum result;
714  TupleDesc tupdesc;
715  HeapTuple tuple;
716 
717  if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
718  elog(ERROR, "return type must be a row type");
719 
721 
722  if (logical_slot)
724  else
726 
727  LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
728 
729  /*
730  * We need to prevent the source slot's reserved WAL from being removed,
731  * but we don't want to lock that slot for very long, and it can advance
732  * in the meantime. So obtain the source slot's data, and create a new
733  * slot using its restart_lsn. Afterwards we lock the source slot again
734  * and verify that the data we copied (name, type) has not changed
735  * incompatibly. No inconvenient WAL removal can occur once the new slot
736  * is created -- but since WAL removal could have occurred before we
737  * managed to create the new slot, we advance the new slot's restart_lsn
738  * to the source slot's updated restart_lsn the second time we lock it.
739  */
740  for (int i = 0; i < max_replication_slots; i++)
741  {
743 
744  if (s->in_use && strcmp(NameStr(s->data.name), NameStr(*src_name)) == 0)
745  {
746  /* Copy the slot contents while holding spinlock */
747  SpinLockAcquire(&s->mutex);
748  first_slot_contents = *s;
749  SpinLockRelease(&s->mutex);
750  src = s;
751  break;
752  }
753  }
754 
755  LWLockRelease(ReplicationSlotControlLock);
756 
757  if (src == NULL)
758  ereport(ERROR,
759  (errcode(ERRCODE_UNDEFINED_OBJECT),
760  errmsg("replication slot \"%s\" does not exist", NameStr(*src_name))));
761 
762  src_islogical = SlotIsLogical(&first_slot_contents);
763  src_restart_lsn = first_slot_contents.data.restart_lsn;
764  temporary = (first_slot_contents.data.persistency == RS_TEMPORARY);
765  plugin = logical_slot ? NameStr(first_slot_contents.data.plugin) : NULL;
766 
767  /* Check type of replication slot */
768  if (src_islogical != logical_slot)
769  ereport(ERROR,
770  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
771  src_islogical ?
772  errmsg("cannot copy physical replication slot \"%s\" as a logical replication slot",
773  NameStr(*src_name)) :
774  errmsg("cannot copy logical replication slot \"%s\" as a physical replication slot",
775  NameStr(*src_name))));
776 
777  /* Copying non-reserved slot doesn't make sense */
778  if (XLogRecPtrIsInvalid(src_restart_lsn))
779  ereport(ERROR,
780  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
781  errmsg("cannot copy a replication slot that doesn't reserve WAL")));
782 
783  /* Overwrite params from optional arguments */
784  if (PG_NARGS() >= 3)
785  temporary = PG_GETARG_BOOL(2);
786  if (PG_NARGS() >= 4)
787  {
788  Assert(logical_slot);
789  plugin = NameStr(*(PG_GETARG_NAME(3)));
790  }
791 
792  /* Create new slot and acquire it */
793  if (logical_slot)
794  {
795  /*
796  * We must not try to read WAL, since we haven't reserved it yet --
797  * hence pass find_startpoint false. confirmed_flush will be set
798  * below, by copying from the source slot.
799  */
801  plugin,
802  temporary,
803  src_restart_lsn,
804  false);
805  }
806  else
808  true,
809  temporary,
810  src_restart_lsn);
811 
812  /*
813  * Update the destination slot to current values of the source slot;
814  * recheck that the source slot is still the one we saw previously.
815  */
816  {
817  TransactionId copy_effective_xmin;
818  TransactionId copy_effective_catalog_xmin;
819  TransactionId copy_xmin;
820  TransactionId copy_catalog_xmin;
821  XLogRecPtr copy_restart_lsn;
822  XLogRecPtr copy_confirmed_flush;
823  bool copy_islogical;
824  char *copy_name;
825 
826  /* Copy data of source slot again */
827  SpinLockAcquire(&src->mutex);
828  second_slot_contents = *src;
829  SpinLockRelease(&src->mutex);
830 
831  copy_effective_xmin = second_slot_contents.effective_xmin;
832  copy_effective_catalog_xmin = second_slot_contents.effective_catalog_xmin;
833 
834  copy_xmin = second_slot_contents.data.xmin;
835  copy_catalog_xmin = second_slot_contents.data.catalog_xmin;
836  copy_restart_lsn = second_slot_contents.data.restart_lsn;
837  copy_confirmed_flush = second_slot_contents.data.confirmed_flush;
838 
839  /* for existence check */
840  copy_name = NameStr(second_slot_contents.data.name);
841  copy_islogical = SlotIsLogical(&second_slot_contents);
842 
843  /*
844  * Check if the source slot still exists and is valid. We regard it as
845  * invalid if the type of replication slot or name has been changed,
846  * or the restart_lsn either is invalid or has gone backward. (The
847  * restart_lsn could go backwards if the source slot is dropped and
848  * copied from an older slot during installation.)
849  *
850  * Since erroring out will release and drop the destination slot we
851  * don't need to release it here.
852  */
853  if (copy_restart_lsn < src_restart_lsn ||
854  src_islogical != copy_islogical ||
855  strcmp(copy_name, NameStr(*src_name)) != 0)
856  ereport(ERROR,
857  (errmsg("could not copy replication slot \"%s\"",
858  NameStr(*src_name)),
859  errdetail("The source replication slot was modified incompatibly during the copy operation.")));
860 
861  /* The source slot must have a consistent snapshot */
862  if (src_islogical && XLogRecPtrIsInvalid(copy_confirmed_flush))
863  ereport(ERROR,
864  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
865  errmsg("cannot copy unfinished logical replication slot \"%s\"",
866  NameStr(*src_name)),
867  errhint("Retry when the source replication slot's confirmed_flush_lsn is valid.")));
868 
869  /* Install copied values again */
871  MyReplicationSlot->effective_xmin = copy_effective_xmin;
872  MyReplicationSlot->effective_catalog_xmin = copy_effective_catalog_xmin;
873 
874  MyReplicationSlot->data.xmin = copy_xmin;
875  MyReplicationSlot->data.catalog_xmin = copy_catalog_xmin;
876  MyReplicationSlot->data.restart_lsn = copy_restart_lsn;
877  MyReplicationSlot->data.confirmed_flush = copy_confirmed_flush;
879 
884 
885 #ifdef USE_ASSERT_CHECKING
886  /* Check that the restart_lsn is available */
887  {
888  XLogSegNo segno;
889 
890  XLByteToSeg(copy_restart_lsn, segno, wal_segment_size);
891  Assert(XLogGetLastRemovedSegno() < segno);
892  }
893 #endif
894  }
895 
896  /* target slot fully created, mark as persistent if needed */
897  if (logical_slot && !temporary)
899 
900  /* All done. Set up the return values */
901  values[0] = NameGetDatum(dst_name);
902  nulls[0] = false;
904  {
906  nulls[1] = false;
907  }
908  else
909  nulls[1] = true;
910 
911  tuple = heap_form_tuple(tupdesc, values, nulls);
912  result = HeapTupleGetDatum(tuple);
913 
915 
916  PG_RETURN_DATUM(result);
917 }
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:1031
#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:1071
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:116
uint32 TransactionId
Definition: c.h:520
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:697
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:3956
void ReplicationSlotsComputeRequiredLSN(void)
Definition: slot.c:804
#define ERROR
Definition: elog.h:43
void ReplicationSlotPersist(void)
Definition: slot.c:732
TransactionId effective_xmin
Definition: slot.h:139
Definition: c.h:616
uint64 XLogSegNo
Definition: xlogdefs.h:41
int errdetail(const char *fmt,...)
Definition: elog.c:957
TransactionId catalog_xmin
Definition: slot.h:77
void ReplicationSlotRelease(void)
Definition: slot.c:476
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:745
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:220
static Datum values[MAXATTR]
Definition: bootstrap.c:167
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define elog(elevel,...)
Definition: elog.h:214
int i
#define NameStr(name)
Definition: c.h:622
ReplicationSlot replication_slots[1]
Definition: slot.h:176
slock_t mutex
Definition: slot.h:116
void CheckLogicalDecodingRequirements(void)
Definition: logical.c:92
void ReplicationSlotsComputeRequiredXmin(bool already_locked)
Definition: slot.c:754
void ReplicationSlotMarkDirty(void)
Definition: slot.c:715
#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:813
void ReplicationSlotCreate(const char *name, bool db_specific, ReplicationSlotPersistency persistency)
Definition: slot.c:222
void wal_segment_open(XLogReaderState *state, XLogSegNo nextSegNo, TimeLineID *tli_p)
Definition: xlogutils.c:788
void DecodingContextFindStartpoint(LogicalDecodingContext *ctx)
Definition: logical.c:518
#define XL_ROUTINE(...)
Definition: xlogreader.h:116
ReplicationSlot * MyReplicationSlot
Definition: slot.c:96
#define Assert(condition)
Definition: c.h:745
void FreeDecodingContext(LogicalDecodingContext *ctx)
Definition: logical.c:561
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:832
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:280

◆ 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:222
void ReplicationSlotSave(void)
Definition: slot.c:697
ReplicationSlotPersistentData data
Definition: slot.h:143
void ReplicationSlotReserveWal(void)
Definition: slot.c:1056
#define XLogRecPtrIsInvalid(r)
Definition: xlogdefs.h:29
ReplicationSlot * MyReplicationSlot
Definition: slot.c:96
#define Assert(condition)
Definition: c.h:745
XLogRecPtr restart_lsn
Definition: slot.h:80
const char * name
Definition: encode.c:561
void ReplicationSlotMarkDirty(void)
Definition: slot.c:715

◆ pg_copy_logical_replication_slot_a()

Datum pg_copy_logical_replication_slot_a ( PG_FUNCTION_ARGS  )

Definition at line 921 of file slotfuncs.c.

References copy_replication_slot().

922 {
923  return copy_replication_slot(fcinfo, true);
924 }
static Datum copy_replication_slot(FunctionCallInfo fcinfo, bool logical_slot)
Definition: slotfuncs.c:700

◆ pg_copy_logical_replication_slot_b()

Datum pg_copy_logical_replication_slot_b ( PG_FUNCTION_ARGS  )

Definition at line 927 of file slotfuncs.c.

References copy_replication_slot().

928 {
929  return copy_replication_slot(fcinfo, true);
930 }
static Datum copy_replication_slot(FunctionCallInfo fcinfo, bool logical_slot)
Definition: slotfuncs.c:700

◆ pg_copy_logical_replication_slot_c()

Datum pg_copy_logical_replication_slot_c ( PG_FUNCTION_ARGS  )

Definition at line 933 of file slotfuncs.c.

References copy_replication_slot().

934 {
935  return copy_replication_slot(fcinfo, true);
936 }
static Datum copy_replication_slot(FunctionCallInfo fcinfo, bool logical_slot)
Definition: slotfuncs.c:700

◆ pg_copy_physical_replication_slot_a()

Datum pg_copy_physical_replication_slot_a ( PG_FUNCTION_ARGS  )

Definition at line 939 of file slotfuncs.c.

References copy_replication_slot().

940 {
941  return copy_replication_slot(fcinfo, false);
942 }
static Datum copy_replication_slot(FunctionCallInfo fcinfo, bool logical_slot)
Definition: slotfuncs.c:700

◆ pg_copy_physical_replication_slot_b()

Datum pg_copy_physical_replication_slot_b ( PG_FUNCTION_ARGS  )

Definition at line 945 of file slotfuncs.c.

References copy_replication_slot().

946 {
947  return copy_replication_slot(fcinfo, false);
948 }
static Datum copy_replication_slot(FunctionCallInfo fcinfo, bool logical_slot)
Definition: slotfuncs.c:700

◆ 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:732
Definition: c.h:616
void ReplicationSlotRelease(void)
Definition: slot.c:476
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:220
const char * name
Definition: encode.c:561
static Datum values[MAXATTR]
Definition: bootstrap.c:167
#define elog(elevel,...)
Definition: elog.h:214
#define NameStr(name)
Definition: c.h:622
void CheckLogicalDecodingRequirements(void)
Definition: logical.c:92
#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:1031
#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:616
void ReplicationSlotRelease(void)
Definition: slot.c:476
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:220
const char * name
Definition: encode.c:561
static Datum values[MAXATTR]
Definition: bootstrap.c:167
#define elog(elevel,...)
Definition: elog.h:214
#define NameStr(name)
Definition: c.h:622
#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:1031
Definition: c.h:616
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:569
#define NameStr(name)
Definition: c.h:622
#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:580
#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:116
#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:91
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:305
int max_slot_wal_keep_size_mb
Definition: xlog.c:110
XLogRecPtr GetXLogWriteRecPtr(void)
Definition: xlog.c:11510
SetFunctionReturnMode returnMode
Definition: execnodes.h:307
#define Max(x, y)
Definition: c.h:921
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:745
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:233
Tuplestorestate * setResult
Definition: execnodes.h:310
static Datum values[MAXATTR]
Definition: bootstrap.c:167
ExprContext * econtext
Definition: execnodes.h:303
#define Int32GetDatum(X)
Definition: postgres.h:479
TupleDesc setDesc
Definition: execnodes.h:311
int errmsg(const char *fmt,...)
Definition: elog.c:824
pid_t active_pid
Definition: slot.h:122
WALAvailability GetWALAvailability(XLogRecPtr targetLSN)
Definition: xlog.c:9507
#define elog(elevel,...)
Definition: elog.h:214
int i
#define CStringGetTextDatum(s)
Definition: builtins.h:87
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  /* Initialize our return value in case we don't do anything */
523 
524  /* invalidate non-timetravel entries */
526 
527  /* Decode at least one record, until we run out of records */
528  while (ctx->reader->EndRecPtr < moveto)
529  {
530  char *errm = NULL;
531  XLogRecord *record;
532 
533  /*
534  * Read records. No changes are generated in fast_forward mode,
535  * but snapbuilder/slot statuses are updated properly.
536  */
537  record = XLogReadRecord(ctx->reader, &errm);
538  if (errm)
539  elog(ERROR, "%s", errm);
540 
541  /*
542  * Process the record. Storage-level changes are ignored in
543  * fast_forward mode, but other modules (such as snapbuilder)
544  * might still have critical updates to do.
545  */
546  if (record)
548 
549  /* Stop once the requested target has been reached */
550  if (moveto <= ctx->reader->EndRecPtr)
551  break;
552 
554  }
555 
556  /*
557  * Logical decoding could have clobbered CurrentResourceOwner during
558  * transaction management, so restore the executor's value. (This is
559  * a kluge, but it's not worth cleaning up right now.)
560  */
561  CurrentResourceOwner = old_resowner;
562 
563  if (ctx->reader->EndRecPtr != InvalidXLogRecPtr)
564  {
566 
567  /*
568  * If only the confirmed_flush LSN has changed the slot won't get
569  * marked as dirty by the above. Callers on the walsender
570  * interface are expected to keep track of their own progress and
571  * don't need it written out. But SQL-interface users cannot
572  * specify their own start positions and it's harder for them to
573  * keep track of their progress, so we should make more of an
574  * effort to save it for them.
575  *
576  * Dirty the slot so it is written out at the next checkpoint. The
577  * LSN position advanced to may still be lost on a crash but this
578  * makes the data consistent after a clean shutdown.
579  */
581  }
582 
584 
585  /* free context, call shutdown callback */
586  FreeDecodingContext(ctx);
587 
589  }
590  PG_CATCH();
591  {
592  /* clear all timetravel entries */
594 
595  PG_RE_THROW();
596  }
597  PG_END_TRY();
598 
599  return retlsn;
600 }
#define NIL
Definition: pg_list.h:65
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
void wal_segment_close(XLogReaderState *state)
Definition: xlogutils.c:813
ResourceOwner CurrentResourceOwner
Definition: resowner.c:142
void wal_segment_open(XLogReaderState *state, XLogSegNo nextSegNo, TimeLineID *tli_p)
Definition: xlogutils.c:788
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:426
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:745
void FreeDecodingContext(LogicalDecodingContext *ctx)
Definition: logical.c:561
XLogRecPtr restart_lsn
Definition: slot.h:80
#define PG_RE_THROW()
Definition: elog.h:336
void LogicalConfirmReceivedLocation(XLogRecPtr lsn)
Definition: logical.c:1363
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:832
#define PG_END_TRY()
Definition: elog.h:320
void ReplicationSlotMarkDirty(void)
Definition: slot.c:715

◆ 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:745
XLogRecPtr restart_lsn
Definition: slot.h:80
slock_t mutex
Definition: slot.h:116
void ReplicationSlotMarkDirty(void)
Definition: slot.c:715

◆ pg_replication_slot_advance()

Datum pg_replication_slot_advance ( PG_FUNCTION_ARGS  )

Definition at line 606 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.

607 {
608  Name slotname = PG_GETARG_NAME(0);
609  XLogRecPtr moveto = PG_GETARG_LSN(1);
610  XLogRecPtr endlsn;
611  XLogRecPtr minlsn;
612  TupleDesc tupdesc;
613  Datum values[2];
614  bool nulls[2];
615  HeapTuple tuple;
616  Datum result;
617 
619 
621 
622  if (XLogRecPtrIsInvalid(moveto))
623  ereport(ERROR,
624  (errmsg("invalid target WAL LSN")));
625 
626  /* Build a tuple descriptor for our result type */
627  if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
628  elog(ERROR, "return type must be a row type");
629 
630  /*
631  * We can't move slot past what's been flushed/replayed so clamp the
632  * target position accordingly.
633  */
634  if (!RecoveryInProgress())
635  moveto = Min(moveto, GetFlushRecPtr());
636  else
637  moveto = Min(moveto, GetXLogReplayRecPtr(&ThisTimeLineID));
638 
639  /* Acquire the slot so we "own" it */
640  (void) ReplicationSlotAcquire(NameStr(*slotname), SAB_Error);
641 
642  /* A slot whose restart_lsn has never been reserved cannot be advanced */
644  ereport(ERROR,
645  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
646  errmsg("replication slot \"%s\" cannot be advanced",
647  NameStr(*slotname)),
648  errdetail("This slot has never previously reserved WAL, or has been invalidated.")));
649 
650  /*
651  * Check if the slot is not moving backwards. Physical slots rely simply
652  * on restart_lsn as a minimum point, while logical slots have confirmed
653  * consumption up to confirmed_flush, meaning that in both cases data
654  * older than that is not available anymore.
655  */
658  else
660 
661  if (moveto < minlsn)
662  ereport(ERROR,
663  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
664  errmsg("cannot advance replication slot to %X/%X, minimum is %X/%X",
665  (uint32) (moveto >> 32), (uint32) moveto,
666  (uint32) (minlsn >> 32), (uint32) minlsn)));
667 
668  /* Do the actual slot update, depending on the slot type */
670  endlsn = pg_logical_replication_slot_advance(moveto);
671  else
672  endlsn = pg_physical_replication_slot_advance(moveto);
673 
674  values[0] = NameGetDatum(&MyReplicationSlot->data.name);
675  nulls[0] = false;
676 
677  /*
678  * Recompute the minimum LSN and xmin across all slots to adjust with the
679  * advancing potentially done.
680  */
683 
685 
686  /* Return the reached position. */
687  values[1] = LSNGetDatum(endlsn);
688  nulls[1] = false;
689 
690  tuple = heap_form_tuple(tupdesc, values, nulls);
691  result = HeapTupleGetDatum(tuple);
692 
693  PG_RETURN_DATUM(result);
694 }
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:927
int errcode(int sqlerrcode)
Definition: elog.c:610
#define LSNGetDatum(X)
Definition: pg_lsn.h:22
XLogRecPtr GetFlushRecPtr(void)
Definition: xlog.c:8421
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:8069
#define OidIsValid(objectId)
Definition: c.h:651
XLogRecPtr confirmed_flush
Definition: slot.h:91
void ReplicationSlotsComputeRequiredLSN(void)
Definition: slot.c:804
#define ERROR
Definition: elog.h:43
XLogRecPtr GetXLogReplayRecPtr(TimeLineID *replayTLI)
Definition: xlog.c:11475
Definition: c.h:616
int errdetail(const char *fmt,...)
Definition: elog.c:957
unsigned int uint32
Definition: c.h:374
void ReplicationSlotRelease(void)
Definition: slot.c:476
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:191
#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:745
XLogRecPtr restart_lsn
Definition: slot.h:80
#define HeapTupleGetDatum(tuple)
Definition: funcapi.h:220
static Datum values[MAXATTR]
Definition: bootstrap.c:167
int errmsg(const char *fmt,...)
Definition: elog.c:824
int ReplicationSlotAcquire(const char *name, SlotAcquireBehavior behavior)
Definition: slot.c:367
#define elog(elevel,...)
Definition: elog.h:214
Definition: slot.h:42
#define NameStr(name)
Definition: c.h:622
static XLogRecPtr pg_physical_replication_slot_advance(XLogRecPtr moveto)
Definition: slotfuncs.c:455
void ReplicationSlotsComputeRequiredXmin(bool already_locked)
Definition: slot.c:754
#define PG_GETARG_NAME(n)
Definition: fmgr.h:278