From: Tom Lane <tgl@sss.pgh.pa.us>
To: Kevin Burke <burke@shyp.com>
Cc: pgsql-bugs@postgresql.org
Subject: Re: UPDATE grabs multiple rows when it seems like it should only grab one
Date: Fri, 22 Apr 2016 19:09:47 -0400
Message-ID: <2934.1461366587@sss.pgh.pa.us> (raw)
In-Reply-To: <CAEYV4pYAG+o2_SO7+Tc9aUF8A9aZW=bNi2H7yd39i9fDy5nEEg@mail.gmail.com>
References: <CAEYV4pYAG+o2_SO7+Tc9aUF8A9aZW=bNi2H7yd39i9fDy5nEEg@mail.gmail.com>
List-Unsubscribe: <mailto:majordomo@postgresql.org?body=unsub%20pgsql-bugs>
Kevin Burke <burke@shyp.com> writes:
> I'm trying to write a job queue that grabs one job at a time from the
> queue. I expect that the following query should update a maximum of one row
> in the table:
> UPDATE queued_jobs
> SET status='in-progress',
> updated_at=now()
> FROM (
> SELECT id AS inner_id
> FROM queued_jobs
> WHERE status='queued'
> AND name = $1
> AND run_after <= now()
> LIMIT 1
> FOR UPDATE
> ) find_job
> WHERE queued_jobs.id = find_job.inner_id
> AND status='queued'
I think you're assuming that the sub-query will always select the same
row, but it doesn't have to. LIMIT without an ORDER BY is ill-defined.
Another problem is that once the outer UPDATE has changed the status
of whichever row the sub-query selects initially, that row isn't
a candidate to be returned by later subquery runs, so it'd certainly
move on to another row. (I'm assuming here that FOR UPDATE allows
the sub-query to see the effects of the outer update immediately,
which might be wrong; I lack the time to go check right now.)
You might have better luck by putting the sub-query in a CTE, where
it will be executed at most once.
regards, tom lane
--
Sent via pgsql-bugs mailing list (pgsql-bugs@postgresql.org)
To make changes to your subscription:
http://www.postgresql.org/mailpref/pgsql-bugs
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Reply to all the recipients from your mail client; the link fills in
the headers below: reply via email
Some clients, webmail especially, drop In-Reply-To and References from
a link, and the reply then starts a new thread: use the mbox below.
To: pgsql-bugs@postgresql.org
Cc: tgl@sss.pgh.pa.us, burke@shyp.com
Subject: Re: UPDATE grabs multiple rows when it seems like it should only grab one
In-Reply-To: <2934.1461366587@sss.pgh.pa.us>
References: <CAEYV4pYAG+o2_SO7+Tc9aUF8A9aZW=bNi2H7yd39i9fDy5nEEg@mail.gmail.com> <2934.1461366587@sss.pgh.pa.us>
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox