Atomically set SERIAL value when committing transaction

后端 未结 1 1472
北恋
北恋 2020-12-30 07:35

Say I have a table where I want to use a serial as primary key to ask for changes from the client. The client will ask \"give me the changes after key X\". With

相关标签:
1条回答
  • 2020-12-30 08:19

    Postgres 9.5 introduced a new feature related to this problem: commit timestamps.

    You just need to activate track_commit_timestamp in postgresql.conf (and restart!) to start tracking commit timestamps. Then you can query:

    SELECT * FROM tbl
    WHERE  pg_xact_commit_timestamp(xmin) >= '2015-11-26 18:00:00+01';
    

    Read the chapter "Commit timestamp tracking" in the Postgres Wiki.
    Related utility functions in the manual.

    Function volatility is only VOLATILE because transaction IDs (xid) can wrap around per definition. So you cannot create a functional index on it.
    You could fake IMMUTABLE volatility in a function wrapper for applications in a limited time frame, but you need to be aware of implications. Related case with more explanation:

    • Does PostgreSQL support "accent insensitive" collations?
    • How do IMMUTABLE, STABLE and VOLATILE keywords effect behaviour of function?

    For many use cases (like yours?) that are only interested in the sequence of commits (and not absolute time) it might be more efficient to work with xmin cast to bigint "directly" (xmin::text::bigint) instead of commit timestamps. (xid is an unsigned integer internally, the upper half that does not fit into a signed integer.) Again, be aware of limitations due to possible xid wraparound.

    For the same reason, commit timestamps are not preserved indefinitely. For small to medium databases, xid wraparound hardly ever happens - but it will eventually if the cluster is live for long enough. Read the chapter "Preventing Transaction ID Wraparound Failures" in the manual for details.

    0 讨论(0)
提交回复
热议问题