FYI the currval() function is safe for doing things like this and should not cause race conditions.
From the PostgreSQL docs:
BTW in new versions of PostgreSQL there is the possibility to use:currval
Return the value most recently obtained by nextval for this sequence in the current session. (An error is reported if nextval has never been called for this sequence in this session.) Notice that because this is returning a session-local value, it gives a predictable answer whether or not other sessions have executed nextval since the current session did.
Code: Select all
INSERT INTO table_name (id, field1, field2, ...) VALUES (default, 'a', 'b', ...) RETURNING id;
And while I'm at it, another thing I've found is when you dump a table made like:
Code: Select all
CREATE TABLE test (id serial);
Code: Select all
CREATE TABLE test (
id integer NOT NULL
);
ALTER TABLE public.test OWNER TO postgres;
CREATE SEQUENCE test_id_seq
START WITH 1
INCREMENT BY 1
NO MAXVALUE
NO MINVALUE
CACHE 1;
ALTER TABLE public.test_id_seq OWNER TO postgres;
ALTER SEQUENCE test_id_seq OWNED BY test.id;
ALTER TABLE test ALTER COLUMN id SET DEFAULT nextval('test_id_seq'::regclass);
Regards,
Ben