简体   繁体   中英

SELECT, check and INSERT if condition is met

I have the following tables: Tour, Customer, TourCustomerXRef. Assuming every Tour has a capacity Cap. Now a request arrives at the backend for a booking.

What I need to do is:

  1. SELECT and count() all of the entries in TourCustomerXRef where the tourid=123
  2. In the program code (or the query?): If count() < Cap
    1. True: INSERT into TourCustomerXRef, return success
    2. False: return an error

However, it might be possible that the backend api is being called concurrently. This could result into the SELECT statement returning a number under the max. capacity both times, resulting in the INSERT being executed multiple times (even though there is just one place left).

What would be the best prevention for above case? set transaction isolation level serializable? or Repeatable Read?

I'm worried that the application logic (even though it's just a simple if) could hurt the performance, since read and write locks would not allow the api to execute querys that just want to select the data without inserting anything, right?

(Using mariaDB)

You can try using lock hint "FOR UPDATE" in the SELECT (mysql example):

BEGIN TRANSACTION;
SELECT * FROM TourCustomerXRef FOR UPDATE WHERE ...;
INSERT ...;
COMMIT;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM