Skip to content

Instantly share code, notes, and snippets.

@mark
Created August 1, 2013 02:14
Show Gist options
  • Save mark/6127910 to your computer and use it in GitHub Desktop.
Save mark/6127910 to your computer and use it in GitHub Desktop.
Reserving primary keys in postgres using Ruby & Sequel
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)
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