lock() / unlock()
The lock()
method allows you to manually lock one or more database tables using MySQL’s LOCK TABLES
mechanism. Use unlock()
to release the lock after your operation is complete. Locking is useful for short-lived critical operations that must not be interrupted.
Signatures:
public function lock(string|array $table): bool
public function unlock(): self
public function setLockMethod(string $method): self
Basic Usage
$db->setLockMethod('WRITE');
$db->lock('test_users');
// Perform critical read/write
$user = $db->where('id', 1)->getOne('test_users');
$db->unlock();
Important:
For row-level locks, use
lock()
uses LOCK TABLES
, which blocks all other access to the table until unlock()
is called.
Use it only for very short and critical sections.For row-level locks, use
setQueryOption('FOR UPDATE')
inside a transaction instead.
Multiple Tables
$db->setLockMethod('READ');
$db->lock(['test_users', 'test_orders']);
// Perform read operations across both tables
$db->unlock();
Return Value
lock()
returnstrue
on success,false
or exception on failureunlock()
always returns the current instance- If
lock()
fails during validation or execution, any partial table locks are automatically released using_unlockOnFailure()
. You don't need to callunlock()
manually in such cases.
Notes
- Only
READ
andWRITE
lock modes are supported viasetLockMethod()
- Calling
lock()
twice withoutunlock()
will throw an exception - If validation fails (e.g. table name),
unlock()
will be auto-called internally - Table prefixing and security validation is automatically applied
lock()
must not be used inside subqueries