Re: Simple Atomic Relationship Insert - Mailing list pgsql-general

From Jim Nasby
Subject Re: Simple Atomic Relationship Insert
Date
Msg-id 54B8C08C.8000609@BlueTreble.com
Whole thread Raw
In response to Re: Simple Atomic Relationship Insert  (Roxanne Reid-Bennett <rox@tara-lu.com>)
Responses Re: Simple Atomic Relationship Insert
Re: Simple Atomic Relationship Insert
Re: Simple Atomic Relationship Insert
List pgsql-general
On 1/15/15 10:57 PM, Roxanne Reid-Bennett 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;

That has a race condition. The only safe way to do this (outside of SSI) is using the example code at
http://www.postgresql.org/docs/devel/static/plpgsql-control-structures.html#PLPGSQL-ERROR-TRAPPING
--
Jim Nasby, Data Architect, Blue Treble Consulting
Data in Trouble? Get it in Treble! http://BlueTreble.com


pgsql-general by date:

Previous
From: Jim Nasby
Date:
Subject: Re: Proper use of pg_xlog_location_diff()
Next
From: Rémi Cura
Date:
Subject: Re: Indexing large table of coordinates with GiST