how do i avoid multiple sessions from inserting the same row?

From: Kolus Maximiliano <Kolus(dot)maximiliano(at)bcr(dot)com(dot)ar>
To: pgsql-general(at)postgresql(dot)org
Subject: how do i avoid multiple sessions from inserting the same row?
Date: 2003-02-24 16:13:11
Message-ID: A56C8EE648A74A4F9653B071E9F71420B6BDEF@bcrweb.bcr.com.ar
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Hello,

I'm programming a little system that has an 'users' table and i've
met a concurrency problems: users will be added to this table upon the
reception of emails from them (for those who want to know, it's like
http://www.ordb.org). So, if john(at)doe(dot)com sends an email to an special
address he wil be added to the users table.

The problem i have is that some users have automated systems that
shoot a lot of emails at once, so i have multiple processes trying to check
if john(at)doe(dot)com exists and add him if he doesnt. The process for this is:

1) SELECT id FROM users WHERE email='blah';
2) If the previous select returns NULL, the user will be added and it's id
will be returned.
3) If the previous select returns the id, it will be returned.

What happened?. Well, two processes believed that john(at)doe(dot)com
didn't exist, both tried to add him and one of them got a beautyfull
duplicated key error.

I need to avoid this, i looked at pg's table and row locking
techniques. I dont know fi SELECT ... FOR UPDATE would work because i would
be selecting a row that doesnt exist yet. LOCK TABLE ... FOR ACCESS
EXCLUSIVE MODE would work, but it seems to be a little extreme for me.

Any ideas or tips?. TIA.

--
Maximiliano A. Kolus
Network Administrator
<kolus(dot)maximiliano(at)bcr(dot)com(dot)ar>
Bolsa De Comercio Rosario - Argentina

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Justin Clift 2003-02-24 16:19:01 Re: A few questions to real pgsql gurus
Previous Message Justin Clift 2003-02-24 16:08:03 Re: A few questions to real pgsql gurus