diff --git a/src/backend/access/transam/xact.c b/src/backend/access/transam/xact.c index 7f412b10d75581b02be473f59ade0c46b96123e5..1654a0e5c739e56f742ad094fd422633d8896c9d 100644 --- a/src/backend/access/transam/xact.c +++ b/src/backend/access/transam/xact.c @@ -391,6 +391,28 @@ GetCurrentTransactionIdIfAny(void) } +/* + * GetStableLatestTransactionIdIfAny + * + * Get the latest XID once and then return same value for rest of transaction. + * Acts as a useful reference point for maintenance tasks. + */ +TransactionId +GetStableLatestTransactionId(void) +{ + static LocalTransactionId lxid = InvalidLocalTransactionId; + static TransactionId stablexid = InvalidTransactionId; + + if (lxid != MyProc->lxid || + !TransactionIdIsValid(stablexid)) + { + lxid = MyProc->lxid; + stablexid = ReadNewTransactionId(); + } + + return stablexid; +} + /* * AssignTransactionId * diff --git a/src/backend/utils/adt/xid.c b/src/backend/utils/adt/xid.c index eeda081ad18adb1f523f69f6cc1086e8fba7da3a..da9da8a29b9b8426f0e0b0b3ef6cdcf7b065649e 100644 --- a/src/backend/utils/adt/xid.c +++ b/src/backend/utils/adt/xid.c @@ -19,6 +19,7 @@ #include "access/transam.h" #include "access/xact.h" #include "libpq/pqformat.h" +#include "storage/proc.h" #include "utils/builtins.h" #define PG_GETARG_TRANSACTIONID(n) DatumGetTransactionId(PG_GETARG_DATUM(n)) @@ -87,16 +88,13 @@ xideq(PG_FUNCTION_ARGS) } /* - * xid_age - compute age of an XID (relative to current xact) + * xid_age - compute age of an XID (relative to latest stable xid) */ Datum xid_age(PG_FUNCTION_ARGS) { TransactionId xid = PG_GETARG_TRANSACTIONID(0); - TransactionId now = GetTopTransactionIdIfAny(); - - if (!TransactionIdIsValid(now)) - now = ReadNewTransactionId(); + TransactionId now = GetStableLatestTransactionId(); /* Permanent XIDs are always infinitely old */ if (!TransactionIdIsNormal(xid)) diff --git a/src/include/access/xact.h b/src/include/access/xact.h index 20e344e5b73a7807368d9659d7e3b19e5eaf87d0..50f181307ff583f645d50e51574499cc8517ac77 100644 --- a/src/include/access/xact.h +++ b/src/include/access/xact.h @@ -209,6 +209,7 @@ extern TransactionId GetTopTransactionId(void); extern TransactionId GetTopTransactionIdIfAny(void); extern TransactionId GetCurrentTransactionId(void); extern TransactionId GetCurrentTransactionIdIfAny(void); +extern TransactionId GetStableLatestTransactionId(void); extern SubTransactionId GetCurrentSubTransactionId(void); extern CommandId GetCurrentCommandId(bool used); extern TimestampTz GetCurrentTransactionStartTimestamp(void);