On 1/15/2015 6:12 PM, Robert DiFalco
wrote:
try this: (if you still get deadlocks, uncomment the advisory lock [thanks Daniel] and try again) Logically I suppose it might run faster to do the select, then insert "if". I almost always write these as insert first - because it's the more restrictive lock. CREATE OR REPLACE FUNCTION select_hometown_id(hometown_name VARCHAR) RETURNS INTEGER AS $BODY$ DECLARE v_id integer; BEGIN -- perform pg_advisory_xact_lock(hashtext(hometown_name)); BEGIN insert into hometowns (name) select hometown_name where not exists (select id from hometowns where name = hometown_name) returning id into v_id; IF (v_id IS NULL) THEN select id into v_id from hometowns where name = hometown_name; END IF; return v_id; EXCEPTION WHEN OTHERS THEN -- choose your poison, this really shouldn't get here END; return null; END; $BODY$ LANGUAGE plpgsql;
-- [At other schools] I think the most common fault in general is to teach students how to pass exams instead of teaching them the science. Donald Knuth |