In my Rails 4 application, I have this query on a Postgres 9.4 database :
@chosen_opportunity = Opportunity.find_by_sql(
" UPDATE \"opportunities\" s
SET opportunity_available = false
FROM (
SELECT \"opportunities\".*
FROM \"opportunities\"
WHERE ( deal_id = #{@deal.id}
AND opportunity_available = true
AND pg_try_advisory_xact_lock(id) )
LIMIT 1
FOR UPDATE
) sub
WHERE s.id = sub.id
RETURNING sub.prize_id, sub.id"
)
Very inspired by this related answer to dba.SE .
I just want my query to find and update the first line (randomly, from LIMIT
), where I available = true
updated it to available = false
, and I need to block the line at the same time, but without creating new requests, waiting for the previous lock to exit, since there are many simultaneous calls , who will use this request.
NOWAIT
FOR UPDATE
. , pg_try_advisory_xact_lock()
NOWAIT
, , :
?