Re: Is "WITH () UPDATE" Thread Safe ?

From: Paul GOERGLER <pgoergler(at)gmail(dot)com>
To: Albe Laurenz <laurenz(dot)albe(at)wien(dot)gv(dot)at>, pgsql-general(at)postgresql(dot)org <pgsql-general(at)postgresql(dot)org>
Subject: Re: Is "WITH () UPDATE" Thread Safe ?
Date: 2014-12-03 05:26:48
Message-ID: etPan.547e9f18.407168d8.94@MacbookAir.local
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Ok thanks.
-- 
Paul GOERGLER

De: Albe Laurenz <laurenz(dot)albe(at)wien(dot)gv(dot)at>
Répondre: Albe Laurenz <laurenz(dot)albe(at)wien(dot)gv(dot)at>>
Date: 1 décembre 2014 at 13:21:07
À: Paul GOERGLER *EXTERN* <pgoergler(at)gmail(dot)com>>, pgsql-general(at)postgresql(dot)org <pgsql-general(at)postgresql(dot)org>>
Sujet:  RE: [GENERAL] Is "WITH () UPDATE" Thread Safe ?

Paul GOERGLER wrote:
> I have a lot of tickets, i need to take a batch of tickets and process them.
> So the process is :
> SELECT ONLY 100 tickets
> PROCESS ticket
> MARK THEM AS « done »
>
> I’m selecting the tickets with :
>
> WITH t0 AS (
> SELECT t.id,
> RANDOM() AS rank,
> EXTRACT(EPOCH FROM NOW() - b.created_at) as elapsed
> FROM tickets AS t
> LEFT JOIN batch as b ON b.id = t.batch_id
> WHERE (
> t.status = 'waiting' OR
> (t.status = 'processing' AND t.locked_until IS NOT NULL AND t.locked_until <= NOW())
> ) AND t.send_at < NOW()
> AND (t.send_before IS NULL OR t.send_before > NOW())
> ORDER BY
> t.priority DESC,
> rank ASC
> LIMIT 100
> FOR UPDATE OF t
> )
> UPDATE tickets AS t1
> SET status = 'processing',
> locked_until = NOW() + '1 HOUR’,
> extra = t1.extra || hstore('elapsed', t0.elapsed || '') || hstore('rank', rank || '')
> FROM t0
> WHERE t1.id = t0.id
> RETURNING t1.*;
>
>
> I wonder if this query is thread safe, Can a ticket be updated between the SELECT part (t0) and the
> UPDATE part ?
> If this query is not « thread safe » how can i do this ?

There is no race condition in your query because you used SELECT ... FOR UPDATE.

That causes the rows found in the WITH clause to be locked against concurrent modification.

So you should be fine.

Yours,
Laurenz Albe

In response to

Browse pgsql-general by date

  From Date Subject
Next Message David G Johnston 2014-12-03 06:15:26 Re: Is "WITH () UPDATE" Thread Safe ?
Previous Message mongoose 2014-12-03 05:05:53 Re: Merge rows based on Levenshtein distance