The error
PDOException: SQLSTATE[42000]: Syntax error or access violation: 1305 SAVEPOINT trans2 does not exist
The testing
I'm writing tests for my apis but I get this strange error in tests where I handle myself some errors using transactions with try-catch statements, e.g.:
public function controllerMethod()
{
try{
DB::beginTransaction();
// do stuff
DB::commit();
return response()->json();
}
catch(\Exception $e){
DB::rollback();
return response()->json([], 500);
}
}
I'm testing on a MySQL db and using the RefreshDatabase trait, and as far as I know in this case since I'm not using an in-memory db the trait perform an optimization executing the migrations only once and wrapping every test in a transaction that is rolled back at the end of each test.
When it occurs
As I said, the error arise only in the tests where I test the correct execution of the catch branch (usually in those test I remove an expected record from the db to cause an exception), while other tests works correctly: it's like that calling myself DB::rollback() mess up with Laravel's DB savepoints handling while testing due the RefreshDatabase trait.
Just to play with it I changed my rollback statement to DB::rollback(DB::transactionLevel() -2 ) and this seems to balance everything, making the test work correctly, but I cannot bring this modification to production.
How can I solve this problem?