My team needs a serial column to increase monotonically with each commit.
There are cases in which two transactions get values 100
and 101
from a sequence, then the 100
transaction takes longer to commit, so the value 101
gets committed first, followed by 100
. This situation is problematic for our needs, and we need to solve for it.
This is exactly the problem described by this question. We need a solution that does not require changes to the database configuration, unlike the accepted answer to that question.
A comment on that solution, as well as this post, suggest using an exclusive transactional advisory lock starting just before the value is acquired.
Is there a way to have Postgres automatically acquire this lock and fetch a value from a sequence when it gets an INSERT
to the table in question?
Note: gaps in the committed values are OK and expected.
EDIT: I have dug into this question enough to be able to ask it well, but I am not very experienced with Postgres. I'm hoping for a pointer to a specific trigger or whatever specific PG setup will accomplish this.