Created
August 1, 2013 02:14
-
-
Save mark/6127910 to your computer and use it in GitHub Desktop.
Reserving primary keys in postgres using Ruby & Sequel
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
conxn = Sequel.postgres(options) | |
pg_array = conxn["SELECT reserve_ids(#{table_name}, #{needed}) AS ids"].first[:ids] | |
new_ids = pg_array.delete('{}').split(',').map(&:to_i) |
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
CREATE OR REPLACE FUNCTION reserve_ids(table_name text, num integer) | |
RETURNS integer[] AS $body$ | |
DECLARE | |
sequence_name text; | |
BEGIN | |
sequence_name = table_name || '_id_seq'; | |
RETURN array_agg(nextval(sequence_name)) FROM generate_series(1, num); | |
END | |
$body$ LANGUAGE plpgsql; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment