Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Table locking issues with Laravel 5.1

I can't lock MySQL tables with this query:

DB::statement('LOCK TABLES imports WRITE');

It gives those exception:

[Illuminate\Database\QueryException]

SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered queries are active. Consider using PDOStatement::fetchAll(). Alternatively, if your code is only ever going to run against mysql, you may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute. (SQL: LOCK TABLES imports WRITE)

The same error occurs when I use PDO.

How i should use this?

like image 823
ekstro Avatar asked Jul 23 '15 08:07

ekstro


2 Answers

If you want to lock the whole table and you want to use LOCK TABLES table_name WRITE it should be called in this way DB::unprepared('LOCK TABLES imports WRITE'); but if you only want to apply the lock on the selected rows then using sharedLock() or lockForUpdate() is the right way to do that so it will return and lock only the selected rows.

like image 91
l3ehnam Avatar answered Oct 14 '22 10:10

l3ehnam


// prevent rows from being modified until you're finished
DB::table('imports')->where('total', '>', 10)->sharedLock()->get();

Use lockForUpdate() to instead prevent rows from being modified or selected with another shared lock.

like image 26
Lance Pioch Avatar answered Oct 14 '22 10:10

Lance Pioch