Skip site navigation (1) Skip section navigation (2)

Re: locking question

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Brian Hirt <bhirt(at)mobygames(dot)com>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: locking question
Date: 2004-04-30 00:30:49
Message-ID: (view raw, whole thread or download thread mbox)
Lists: pgsql-general
Brian Hirt <bhirt(at)mobygames(dot)com> writes:
> I don't have much experience with locking, because I haven't really 
> needed to use it.  Any advice would be greatly helpful.   Belew is 
> basically the transaction I'm running -- it fails when a 2nd one starts 
> while the 1st is still running.

> delete from blah_stats where id = 1
> insert into blah_stats select id,count(*) from blah where id = 1 group 
> by id

That will fail if both xacts are trying to act on id 1 (I'm assuming
there are various different id values that could be involved?).  The
most general solution is to add a retry loop and use SERIALIZABLE mode.
(In general, writer transactions in SERIALIZABLE mode will always need
a retry loop.)

Another possibility, if the set of id's in use is not changing fast,
is to assume that there's probably already a row with the right ID
value and just update it.

	UPDATE blah_stats SET count = (select count(*) from blah where
id = 1) WHERE id = 1;
	IF zero rows updated THEN insert as above; END IF;

You need to run this in READ COMMITTED mode so that concurrent UPDATEs
won't burp.  This can still fail, if two transactions try to insert the
same new row at about the same time, but you may not care too much (the
first one probably inserted the right value, or close enough...)

Plan C is to take out a write-exclusive lock on blah_stats at the start
of the transaction.  This avoids all the funny cases at the cost of
preventing concurrent updates for different ID values.  If your usage
pattern is such that that's not a big hit, this is the way to go.

			regards, tom lane

In response to

pgsql-general by date

Next:From: Tatsuo IshiiDate: 2004-04-30 01:20:32
Subject: Re: Postgre and Web Request
Previous:From: Tom LaneDate: 2004-04-30 00:15:32
Subject: Re: Optimizer choosing smaller index instead of right one

Privacy Policy | About PostgreSQL
Copyright © 1996-2017 The PostgreSQL Global Development Group