- A good article on DB::RAW
- Some general examples
- Racing condition:
- Breaking Laravel’s firstOrCreate using race conditions
- To solve this problem there are a couple of solutions. You could set the amount of processes of the queue to 1 so multiple jobs won’t be executed concurrently. If you go that route I’d recommend scheduling the jobs on another queue, so the default
queue
can still use multiple processes. You could also solve it on the database level. There’s anINSERT INTO .. ON DUPLICATE KEY
that you can leverage. You’ll find an example in this gist on GitHub.
- To solve this problem there are a couple of solutions. You could set the amount of processes of the queue to 1 so multiple jobs won’t be executed concurrently. If you go that route I’d recommend scheduling the jobs on another queue, so the default
- Laravel, Queues, Eloquent, and Race Conditions — FirstOrCreate
- Using mysql statement directly
- this method is prone to race condition. the select and insert are not executed as one atomic operation but as 2 individual operations. so between the select and insert, some other process might do an insert
- Why
SELECT ... FOR UPDATE
doesn’t work on non-existent rows like you might think it does- Use a lock via the mysql
GET_LOCK
/RELEASE_LOCK
functions. If you include the primary key value(s) in the lock name, you can avoid having a global lock on the whole table, the lock names act effectively as row locks. Beware that MySQL earlier than 5.7.5 limits you to one lock per session
- Use a lock via the mysql
- Laravel Pessimistic Locking
- MySQL set isolation level to avoid racing condition
- MySQL or Laravel transaction
- https://dba.stackexchange.com/questions/166242/mysql-will-a-transaction-lock-the-row/166268
- https://dba.stackexchange.com/questions/166242/mysql-will-a-transaction-lock-the-row/166268
-
SELECT something FOR UPDATE;
This tells other connections “I intend to update the row; please don’t mess me up”.
Also, beware of deadlock
-
- Laravel database transaction
- If an Exception of any kind is thrown within the closure, then the transaction is rolled back. This means that if there’s a SQL error (one that would not normally fail silently), then the transaction is rolled back
- Breaking Laravel’s firstOrCreate using race conditions
- Laravel Builder API
- Has interface for insertusing, insertignore….
- Eloquent insert update examples