Isolation level required for reliable division / enlargement in one field

Suppose we have a table as follows:

+----+---------+--------+
| id | Name    | Bunnies|
+----+---------+--------+
|  1 | England |   1000 |
|  2 | Russia  |   1000 |
+----+---------+--------+

And we have several users who remove rabbits for a certain period, for example, 2 hours. (So ​​at least 0 rabbits, not more than 1000 rabbits, rabbits are returned, not added by users)

I use two basic transactional queries like

BEGIN;
  UPDATE `BunnyTracker` SET `Bunnies`=`Bunnies`+1 where `id`=1;
COMMIT;

When someone returns the rabbit and

BEGIN;
  UPDATE `BunnyTracker` SET `Bunnies`=`Bunnies`-1 where `id`=1 AND `Bunnies` > 0;
COMMIT;

When someone tries to take a rabbit. I assume that these requests will implement some kind of atomicity under the hood

It is imperative that users cannot take more rabbits than each country (i.e. -23 bunnies if 23 users complete transactions simultaneously)

, ACID , // , (0-1000) , , .

- ?

+3
2

, , increment decrement .

, Bunnies = 1, , 1. , , 1 0. , .

, SELECT ... FOR UPDATE, . :

BEGIN;
  SELECT `Bunnies` FROM `BunnyTracker` where `id`=1 FOR UPDATE;
  UPDATE `BunnyTracker` SET `Bunnies`=`Bunnies`+1 where `id`=1;
COMMIT;
+2

, , , . (, / ).

, "bunnies >= 0" , ?

+1

Source: https://habr.com/ru/post/1787186/


All Articles