How to block table to booking? My booking table has from_datetime and to_datetime fields. I would like to avoid situation, when two users book something in the same time.
My attempts:
TERMINAL 1: – user1
LOCK TABLE booking READ; INSERT INTO booking VALUES ('2019-01-01 12:00:00', '2019-01-01 14:00:00');
Now table booking should be locked, and other users should not be able to read from its, but…
TERMINAL 2: – user2
SELECT * from booking
I have results… Why? This should be blocked until I do in TERMINAL 1:
unlock tables;
Advertisement
Answer
You need to use LOCK TABLE booking WRITE;
. That indicates that you’re going to be writing to the table, and you need to block everyone else from reading and writing the table.
A READ
lock means that you’re only going to read the table. It blocks other users from writing to the table, so that all your reads access consistent table contents. But it doesn’t block other users from reading the table.
However, if you’re using InnoDB you should use transactions rather than table locks. This is more fine-grained, and figures out what to lock automatically. Your code would look something like this:
START TRANSACTION; SELECT COUNT(*) FROM booking WHERE from_datetime = '2019-01-01 12:00:00' AND to_datetime = '2019-01-01 14:00:00' FOR UPDATE; -- If this returns zero count: INSERT INTO booking VALUES ('2019-01-01 12:00:00', '2019-01-01 14:00:00'); COMMIT;
The FOR UPDATE
option in the SELECT
causes MySQL to lock the appropriate part of the table. If another user executes the same code, they’ll be blocked if they try to select the same times.