Last active
January 24, 2024 23:06
-
-
Save nathansgreen/f4956e64584b3bb0ff68dd2f456313d5 to your computer and use it in GitHub Desktop.
Postgres Sequence Bulk Increment
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- I needed a way to safely pull a bunch of sequence values to my client in order to bulk | |
-- insert many thousands of rows. I'm doing this because I don't want to use 128-bit keys. | |
-- I found this: | |
-- https://www.depesz.com/2008/03/20/getting-multiple-values-from-sequences/ | |
select pg_advisory_lock(123); | |
alter sequence seq increment by 1000; | |
select nextval('seq'); | |
alter sequence seq increment by 1; | |
select pg_advisory_unlock(123); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- note that if the sequence's `cache` value is > 1 this will end up | |
-- setting the sequence value to `nextval + increment * cache` | |
create or replace function multi_nextval(seqname text, increment int4) | |
returns bigint as $$ | |
declare | |
seq text; | |
lock bigint; | |
reply bigint; | |
begin | |
select quote_ident(seqname) into seq; | |
select hashtextextended(seqname, 883669774654) into lock; | |
perform pg_advisory_lock(lock); | |
execute 'alter sequence ' || seq || ' increment by ' || increment::text; | |
reply := nextval(seqname); | |
execute 'alter sequence ' || seq || ' increment by 1'; | |
perform pg_advisory_unlock(lock); | |
return reply; | |
end | |
$$ language 'plpgsql'; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment