Last updated
Last updated
Within InnoDB, all locks are put on index.
Only when rollback or commit happens, the lock will be released.
SELECT ... FOR UPDATE will easily cause deadlocks.
Deadlock pattern
Use optimistic lock to replace pessimistic pattern.
Deadlock example
Def: If transaction T1 holds a shared (S) lock on row r, then requests from some distinct transaction T2 for a lock on row r are handled as follows:
A request by T2 for an S lock can be granted immediately. As a result, both T1 and T2 hold an S lock on r.
A request by T2 for an X lock cannot be granted immediately.
Add lock:
select ...from XXX where YYY lock in share mode
insert ... into select ...
Release lock: commit / rollback
Def: If a transaction T1 holds an exclusive (X) lock on row r, a request from some distinct transaction T2 for a lock of either type on r cannot be granted immediately. Instead, transaction T2 has to wait for transaction T1 to release its lock on row r.
Add lock: Automatically by default
update
delete
insert
select ... from XXX where YYY from update
If there is no index on YYY, then it will lock the entire table.
Release lock: commit / rollback
Goal: Divide the operation for adding lock into multiple phases. This is especially useful in cases of table locks.
Operation: Automatically added by database. If a shared lock needs to be acquired, then an intentional shared lock needs to be acquired first; If an exclusive lock needs to be acquired, then an intentional exclusive lock needs to be acquired first.
Row lock implementation is based on index
If the query does not hit any index, then only table lock could be used.
Add:
Lock Table tableName READ
Lock Table tableName WRITE
discard table
import
Release:
Commit / Rollback
Be triggered automatically when insert ... into Table xxx happens
By default use next key locks except the following two cases: *
Both needs to be met:
"Where condition" uses exact match (==) and the record exists.
"Where condition" uses primary key or unique index.
Gap lock only exists in repeatable read isolation level.
Typically gap lock is open on both the "OPEN" and "CLOSE" part.
One of the following:
Where condition uses exact match (==) on a unique index and the record does not exist.
Where condition uses range match (>, <,>) on a unique index.
Where condition has index but is not unique index.
If it is not covered by gap lock and record lock.
Relationship with other locks:
Next key = record lock + gap lock + record on the right border