I want to increment a sequence by some batchSize in PostgreSQL but I am not sure if this query is safe from concurrent calls made to the same sequence.
select setval('my_sequence', nextval('my_sequence') + batchSize);
What I am worried bout given the query above is that the call for setval() of the sequence would set the sequence back or perhaps abort the query since if another thread has fetched it nextval() concurrently.
For example:
Thread 1. nextval = 1001 batchSize = 100 sets sequence to 1101
Tread 2. nextval = 1002 batchSize = 20 sets sequence to 1022
This would mean that the sequence could ultimately return duplicate sequenceIds for for ids between 1002 and 1101.
The same could be achieved using the generate_series() function. The drawback would be that the series is not guaranteed to be in sequence since other threads can be calling nextval() concurrently to the same sequence which means that I have to fetch and parse the generated series.