Songo
Songo

Reputation: 5736

Preventing 2 users from updating the same record simultaneously

I have a table tbl_orders. It has a quantity field quantity. In some part of my application I need to decrement the quantity by 1.

I already know the id of the record (available from the client side), so I issue an update statement:

UPDATE tbl_orders
SET quantity=quantity-1
WHERE id= 6 

The problem is that this query can accidentally be run multiple times concurrently. For example, 2 customer service operators may update the same record simultaneously. That means that the quantity will be decremented by 2 when it is supposed to be decremented once only.

I tried putting the update in a transaction, but that resulted in only delaying the second transaction until the first one was committed. Once it was committed the second update ran and decremented the record again.

How can I make sure that other queries fail if one is modifying a record?

UPDATE:

for an update to be valid the quantity on the client side was the same in the database. For example if a user sees a quantity 5 on his browser and wants to decrement it, the value in database must be the same.

UPDATE 2

I found a good explanation here for optimistic locking using Doctrine 2:

Upvotes: 3

Views: 7204

Answers (1)

DRapp
DRapp

Reputation: 48139

One approach I've used/seen in the past was having a timestamp column. When querying, ensure you have both the ID and the original timestamp at the start of editing the record. Then, when you are trying to update, send via

update YourTable
   set counter = counter -1,
       TheTimestampColumn = new timestamp value
   where ID = yourID
     and TheTimeStampColumn = timeStampEditStartedWith

This way, whoever gets to it first with the original starting timestamp would win. For the one following, you would have to track how many records were updated, and if that count equals zero, then you would notify the user that another person made a change to the record while you were viewing it. Do you want to reload the latest data? (or something like that).

Upvotes: 8

Related Questions