I try to use Pessimistic Locking with Doctrine ORM for PostgreSql. Doctrine and PostgreSql with default configurations (without any changes).
This is code example (Symfony Command).
$sleep
- this is time in seconds
$manager = $this->getContainer()->get('mmi.manager.message');
$conn = $manager->em()->getConnection();
$manager->em()->getConnection()->beginTransaction();
try {
$entity = $manager->repo()->find('cd7eb9e9', LockMode::PESSIMISTIC_WRITE);
$entity->setState(EntityActionInterface::STATE_IN_PROGRESS);
$manager->em()->persist($entity);
$manager->em()->flush();
$ts = (new \DateTime())->getTimestamp();
$output->writeln("TS: {$ts}");
if ($sleep) {
$output->writeln("Sleep: {$sleep}");
sleep($sleep);
}
$entity->setMessage([$ts]);
$manager->em()->persist($entity);
$manager->em()->flush();
$conn->commit();
} catch (PessimisticLockException $ex) {
var_dump(get_class($ex));
$conn->rollBack();
throw $ex;
} catch (\Exception $ex) {
var_dump(get_class($ex));
$conn->rollBack();
throw $ex;
}
How tested
Run two command. First command runs with timeout 20 seconds. Second command runs without any timeout.
Expected result
Second command throws PessimisticLockException
Actual result
Second command waits for first transaction commit and then updates row.
Question
What should I do to make Doctrine throw PessimisticLockException
if row is now locked?