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();

Multiple Tables

$db->setLockMethod('READ');
$db->lock(['test_users', 'test_orders']);

// Perform read operations across both tables

$db->unlock();

Return Value

  • lock() returns true on success, false or exception on failure
  • unlock() 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 call unlock() manually in such cases.

Notes

  • Only READ and WRITE lock modes are supported via setLockMethod()
  • Calling lock() twice without unlock() 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

See Also