Skip to content

Commit 7b67f7b

Browse files
committed
Cover possible no-db related throw before touching the db
Address doctrine#6545 (comment)
1 parent 49dabe6 commit 7b67f7b

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

src/Connection.php

+15-1
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
use Doctrine\DBAL\Connection\StaticServerVersionProvider;
1313
use Doctrine\DBAL\Driver\API\ExceptionConverter;
1414
use Doctrine\DBAL\Driver\Connection as DriverConnection;
15+
use Doctrine\DBAL\Driver\Exception as TheDriverException;
1516
use Doctrine\DBAL\Driver\Statement as DriverStatement;
1617
use Doctrine\DBAL\Exception\CommitFailedRollbackOnly;
1718
use Doctrine\DBAL\Exception\ConnectionLost;
@@ -939,7 +940,20 @@ public function transactional(Closure $func): mixed
939940
}
940941
}
941942

942-
$this->commit();
943+
$shouldRollback = true;
944+
try {
945+
$this->commit();
946+
947+
$shouldRollback = false;
948+
} catch (TheDriverException $t) {
949+
$shouldRollback = false;
950+
951+
throw $t;
952+
} finally {
953+
if ($shouldRollback) {
954+
$this->rollBack();
955+
}
956+
}
943957

944958
return $res;
945959
}

tests/ConnectionTest.php

+22
Original file line numberDiff line numberDiff line change
@@ -644,4 +644,26 @@ public function rollBack(): void
644644
self::assertSame('Original exception', $e->getPrevious()->getMessage());
645645
}
646646
}
647+
648+
/**
649+
* We are not sure if this can happen in real life scenario
650+
*/
651+
public function testItFailsDuringCommitBeforeTouchingDb(): void
652+
{
653+
$connection = new class (['memory' => true], new Driver\SQLite3\Driver()) extends Connection {
654+
public function commit(): void
655+
{
656+
throw new \Exception('Fail before touching the db');
657+
}
658+
659+
public function rollBack(): void
660+
{
661+
throw new \Exception('Rollback got triggered');
662+
}
663+
};
664+
665+
$this->expectExceptionMessage('Rollback got triggered');
666+
$connection->transactional(static function (): void {
667+
});
668+
}
647669
}

0 commit comments

Comments
 (0)