Friday, November 14, 2014

Locking Data in Laravel

Locking Data:

There are two mechanisms for locking data in a database.

1. Pessimistic locking

2. Optimistic locking

In pessimistic locking a record or page is locked immediately when the lock is requested, while in an optimistic lock the record or page is only locked when the changes made to that record are updated.

The latter situation is only appropriate when there is less chance of someone needing to access the record while it is locked; otherwise it cannot be certain that the update will succeed because the attempt to update the record will fail if another user updates the record first.

With pessimistic locking it is guaranteed that the record will be updated.

The query builder includes a few functions to help you do "pessimistic locking" on your SELECT statements.

To run the SELECT statement with a "shared lock", you may use the sharedLock method on a query:


DB::table('users')->where('votes', '>', 100)->sharedLock()->get();


To "lock for update" on a SELECT statement, you may use the lockForUpdate method on a query:

DB::table('users')->where('votes', '>', 100)->lockForUpdate()->get();



Thanks

1 comment: