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

From Daniel Verite
Subject Re: Simple Atomic Relationship Insert
Date
Msg-id 6de97c32-a025-4184-975a-a2b2210bd28c@mm
Whole thread Raw
In response to Re: Simple Atomic Relationship Insert  (Roxanne Reid-Bennett <rox@tara-lu.com>)
Responses Re: Simple Atomic Relationship Insert
List pgsql-general
    Roxanne Reid-Bennett wrote:

> When you have a sequence of steps that need to be serialized across
> processes, choose or even create a table to use for locking

This can also be done with an advisory lock, presumably faster:
http://www.postgresql.org/docs/current/static/explicit-locking.html

DECLARE
   lock_key int := hashtext(hometown_name);
BEGIN
   SELECT pg_advisory_xact_lock(lock_key,0);
   // check for existence and insert if it doesn't exist
END;

When several sessions try to insert the same town (or strictly speaking, with
the same hash), only one of them will be allowed to proceed, the others being
put to wait until the first one commits or rollbacks, and so on until every
session gets through. The lock is automatically released at the end of the
transaction. It makes no difference if the "check and insert" is crammed into
a single SQL statement or several statements in procedural style.

This technique is intended to work with the default "Read Committed"
isolation level, which allows the concurrent transactions to "see" the new
row inserted  by the single other transaction that got the "it does not yet
exist" result in  the check for existence, and proceeded to insert and
eventually commit.

Best regards,
--
Daniel
PostgreSQL-powered mail user agent and storage: http://www.manitou-mail.org


pgsql-general by date:

Previous
From: Roxanne Reid-Bennett
Date:
Subject: Re: Simple Atomic Relationship Insert
Next
From: Sameer Kumar
Date:
Subject: Re: [HACKERS] Check that streaming replica received all data after master shutdown