Skip to content

Commit 1a4bc2d

Browse files
Ensure age() returns a stable value rather than the latest value
1 parent 153b1db commit 1a4bc2d

File tree

3 files changed

+26
-5
lines changed

3 files changed

+26
-5
lines changed

src/backend/access/transam/xact.c

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -393,6 +393,28 @@ GetCurrentTransactionIdIfAny(void)
393393
}
394394

395395

396+
/*
397+
* GetStableLatestTransactionIdIfAny
398+
*
399+
* Get the latest XID once and then return same value for rest of transaction.
400+
* Acts as a useful reference point for maintenance tasks.
401+
*/
402+
TransactionId
403+
GetStableLatestTransactionId(void)
404+
{
405+
static LocalTransactionId lxid = InvalidLocalTransactionId;
406+
static TransactionId stablexid = InvalidTransactionId;
407+
408+
if (lxid != MyProc->lxid ||
409+
!TransactionIdIsValid(stablexid))
410+
{
411+
lxid = MyProc->lxid;
412+
stablexid = ReadNewTransactionId();
413+
}
414+
415+
return stablexid;
416+
}
417+
396418
/*
397419
* AssignTransactionId
398420
*

src/backend/utils/adt/xid.c

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
#include "access/transam.h"
2020
#include "access/xact.h"
2121
#include "libpq/pqformat.h"
22+
#include "storage/proc.h"
2223
#include "utils/builtins.h"
2324

2425
#define PG_GETARG_TRANSACTIONID(n) DatumGetTransactionId(PG_GETARG_DATUM(n))
@@ -87,16 +88,13 @@ xideq(PG_FUNCTION_ARGS)
8788
}
8889

8990
/*
90-
* xid_age - compute age of an XID (relative to current xact)
91+
* xid_age - compute age of an XID (relative to latest stable xid)
9192
*/
9293
Datum
9394
xid_age(PG_FUNCTION_ARGS)
9495
{
9596
TransactionId xid = PG_GETARG_TRANSACTIONID(0);
96-
TransactionId now = GetTopTransactionIdIfAny();
97-
98-
if (!TransactionIdIsValid(now))
99-
now = ReadNewTransactionId();
97+
TransactionId now = GetStableLatestTransactionId();
10098

10199
/* Permanent XIDs are always infinitely old */
102100
if (!TransactionIdIsNormal(xid))

src/include/access/xact.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -198,6 +198,7 @@ extern TransactionId GetTopTransactionId(void);
198198
extern TransactionId GetTopTransactionIdIfAny(void);
199199
extern TransactionId GetCurrentTransactionId(void);
200200
extern TransactionId GetCurrentTransactionIdIfAny(void);
201+
extern TransactionId GetStableLatestTransactionId(void);
201202
extern SubTransactionId GetCurrentSubTransactionId(void);
202203
extern CommandId GetCurrentCommandId(bool used);
203204
extern TimestampTz GetCurrentTransactionStartTimestamp(void);

0 commit comments

Comments
 (0)