Search code examples
postgresqlwallogical-replication

Is it possible to get the current 64 bit transactionId (with the epoch) in a postgreSQL logical replication plugin


I am building a Change Capture system that consumes the Postgres WAL through a logical decoding output plugin.

In the callbacks it is very easy to access the current transactionId (https://doxygen.postgresql.org/structReorderBufferTXN.html#ad3ff4a8f320f2ec21e3e07688d29c741) but this is the 32 bit one that can wrap around after 4B commits, thus it is not reliable as a logical counter.

Postgres internally maintains a 64 bit transactionID that does not wrap around (select txid_current()) : https://www.postgresql.org/docs/9.4/functions-info.html#FUNCTIONS-TXID-SNAPSHOT

https://github.com/postgres/postgres/blob/3412030205211079f9b0510e2244083e4ee7b15a/src/backend/access/transam/xact.c#L473-L488

Is it possible to access this ID from a logical decoding plugin? And if not, what is the reason for it?

Thanks


Solution

  • You have two options:

    1. You use OidFunctionCall0 to call the SQL function txid_current().

    2. You copy the code from txid_current, load_xid_epoch and convert_xid from src/backend/utils/adt/txid.c.

    The second option will be faster, but you have to duplicate code.