EspoCRM – Open Source CRM Application
PHP calendarcontactscrmcrm-platformcrm-systemcustomer-portalcustomer-supportcustomizabledocumentsemail-marketingkanbanleadsopen-sourcephpplatformsales-automationsingle-page-applicationsupport
ORM: Deadlock in transaction handling
Yurii669fc3f15f65
diff --git a/application/Espo/ORM/Exceptions/DeadlockException.php b/application/Espo/ORM/Exceptions/DeadlockException.phpnew file mode 100644index 0000000000..7dc05b537d--- /dev/null+++ b/application/Espo/ORM/Exceptions/DeadlockException.php@@ -0,0 +1,38 @@+<?php+/************************************************************************+ * This file is part of EspoCRM.+ *+ * EspoCRM – Open Source CRM application.+ * Copyright (C) 2014-2026 EspoCRM, Inc.+ * Website: https://www.espocrm.com+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as published by+ * the Free Software Foundation, either version 3 of the License, or+ * (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <https://www.gnu.org/licenses/>.+ *+ * The interactive user interfaces in modified source and object code versions+ * of this program must display Appropriate Legal Notices, as required under+ * Section 5 of the GNU Affero General Public License version 3.+ *+ * In accordance with Section 7(b) of the GNU Affero General Public License version 3,+ * these Appropriate Legal Notices must retain the display of the "EspoCRM" word.+ ************************************************************************/++namespace Espo\ORM\Exceptions;++use RuntimeException;++/**+ * @since 10.1.0+ */+class DeadlockException extends RuntimeException+{}diff --git a/application/Espo/ORM/Executor/DefaultSqlExecutor.php b/application/Espo/ORM/Executor/DefaultSqlExecutor.phpindex b968d9ca59..f2081f0593 100644--- a/application/Espo/ORM/Executor/DefaultSqlExecutor.php+++ b/application/Espo/ORM/Executor/DefaultSqlExecutor.php@@ -29,6 +29,7 @@namespace Espo\ORM\Executor;+use Espo\ORM\Exceptions\DeadlockException;use Espo\ORM\PDO\PDOProvider;use Psr\Log\LoggerInterface;@@ -73,16 +74,28 @@ class DefaultSqlExecutor implements SqlExecutor{$counter = $counter ?? self::MAX_ATTEMPT_COUNT;+ $inTransaction = $this->pdo->inTransaction();+try {$sth = $this->pdo->query($sql);} catch (Exception $e) {$counter--;- if ($counter === 0 || !$this->isExceptionIsDeadlock($e)) {+ $isDeadlock = $this->isExceptionIsDeadlock($e);++ if (+ $counter === 0 ||+ !$isDeadlock ||+ $inTransaction+ ) {if ($this->logFailed) {$this->logger?->error("SQL failed: " . $sql, ['isSql' => true]);}+ if ($isDeadlock) {+ throw new DeadlockException(previous: $e);+ }+/** @var PDOException $e */throw $e;}@@ -99,10 +112,16 @@ class DefaultSqlExecutor implements SqlExecutorprivate function isExceptionIsDeadlock(Exception $e): bool{- if (!$e instanceof PDOException) {+ if (!$e instanceof PDOException || !$e->errorInfo) {return false;}- return isset($e->errorInfo) && $e->errorInfo[0] == 40001 && $e->errorInfo[1] == 1213;+ $state = $e->errorInfo[0] ?? null;++ if ($state === '40P01') {+ return true;+ }++ return $state === '40001' && (int) $e->errorInfo[1] === 1213;}}diff --git a/application/Espo/ORM/Executor/QueryExecutor.php b/application/Espo/ORM/Executor/QueryExecutor.phpindex 4185cab748..ff2151502d 100644--- a/application/Espo/ORM/Executor/QueryExecutor.php+++ b/application/Espo/ORM/Executor/QueryExecutor.php@@ -29,6 +29,7 @@namespace Espo\ORM\Executor;+use Espo\ORM\Exceptions\DeadlockException;use Espo\ORM\Query\Query;use PDOStatement;@@ -40,6 +41,8 @@ interface QueryExecutor{/*** Execute a query.+ *+ * @throws DeadlockException*/public function execute(Query $query): PDOStatement;}diff --git a/application/Espo/ORM/TransactionManager.php b/application/Espo/ORM/TransactionManager.phpindex ebf93784aa..601045ed5d 100644--- a/application/Espo/ORM/TransactionManager.php+++ b/application/Espo/ORM/TransactionManager.php@@ -29,6 +29,7 @@namespace Espo\ORM;+use Espo\ORM\Exceptions\DeadlockException;use Espo\ORM\QueryComposer\QueryComposer;use PDO;@@ -41,6 +42,8 @@ class TransactionManager{private int $level = 0;+ private const int MAX_ATTEMPT_COUNT = 4;+public function __construct(private PDO $pdo, private QueryComposer $queryComposer){}@@ -65,20 +68,38 @@ class TransactionManager** @return mixed A function result.*/- public function run(Closure $function)+ public function run(Closure $function): mixed{+ return $this->runInternal($function);+ }++ /**+ * @throws PDOException+ */+ private function runInternal(Closure $function, ?int $counter = null): mixed+ {+ $counter ??= self::MAX_ATTEMPT_COUNT;+$this->start();try {$result = $function();$this->commit();+ } catch (DeadlockException $e) {+ $this->level --;+ $counter --;++ if ($counter === 0) {+ /** @noinspection PhpUnhandledExceptionInspection */+ throw $e->getPrevious() ?? new RuntimeException();+ }++ return $this->runInternal($function, $counter);} catch (Throwable $e) {$this->rollback();- /**- * @var PDOException $e- */+ /** @var PDOException $e */throw $e;}diff --git a/tests/unit/Espo/ORM/SqlExecutorTest.php b/tests/unit/Espo/ORM/SqlExecutorTest.phpindex 721f4d8359..93547b841c 100644--- a/tests/unit/Espo/ORM/SqlExecutorTest.php+++ b/tests/unit/Espo/ORM/SqlExecutorTest.php@@ -29,6 +29,7 @@namespace tests\unit\Espo\ORM;+use Espo\ORM\Exceptions\DeadlockException;use Espo\ORM\Executor\DefaultSqlExecutor;use Espo\ORM\PDO\PDOProvider;@@ -40,7 +41,7 @@ use RuntimeException;class SqlExecutorTest extends TestCase{- private $pdo;+ private ?PDO $pdo = null;private $sth;private $executor;@@ -138,7 +139,7 @@ class SqlExecutorTest extends TestCase$e = new PDOException;- $e->errorInfo = [40001, 1213];+ $e->errorInfo = ['40001', 1213];$invokedCount = $this->exactly(2);@@ -161,4 +162,28 @@ class SqlExecutorTest extends TestCase$this->assertInstanceOf(PDOStatement::class, $sth);}++ public function testExecuteDeadlockInTransaction(): void+ {+ $sql = "SOME QUERY";++ $e = new PDOException();+ $e->errorInfo = ['40001', 1213];++ $this->pdo+ ->expects($this->once())+ ->method('inTransaction')+ ->willReturn(true);++ $this->expectException(DeadlockException::class);++ $this->pdo+ ->expects($this->once())+ ->method('query')+ ->willReturnCallback(function () use ($e) {+ throw $e;+ });++ $this->executor->execute($sql, true);+ }}diff --git a/tests/unit/Espo/ORM/TransactionManagerTest.php b/tests/unit/Espo/ORM/TransactionManagerTest.phpindex b94ade64cb..599b50bf50 100644--- a/tests/unit/Espo/ORM/TransactionManagerTest.php+++ b/tests/unit/Espo/ORM/TransactionManagerTest.php@@ -29,9 +29,11 @@namespace tests\unit\Espo\ORM;+use Espo\ORM\Exceptions\DeadlockException;use Espo\ORM\QueryComposer\MysqlQueryComposer;use Espo\ORM\TransactionManager;use PDO;+use PDOException;use PHPUnit\Framework\TestCase;use RuntimeException;@@ -273,4 +275,31 @@ class TransactionManagerTest extends TestCase);} catch (RuntimeException $e) {}}++ public function testDeadlock(): void+ {+ $this->pdo+ ->expects($this->exactly(4))+ ->method('beginTransaction');++ $this->pdo+ ->expects($this->never())+ ->method('rollback');++ $counter = 0;+ $thrown = false;++ try {+ $this->manager->run(function () use (&$counter) {+ $counter ++;++ throw new DeadlockException(previous: new PDOException());+ });+ } catch (PDOException) {+ $thrown = true;+ }++ $this->assertTrue($thrown);+ $this->assertEquals(4, $counter);+ }}