Skip to content

Commit 220aec4

Browse files
committed
Merge branch '3.9.x' into 4.2.x
* 3.9.x: Run risky code in finally block (doctrine#6543)
2 parents dadd353 + c204fe1 commit 220aec4

File tree

2 files changed

+30
-4
lines changed

2 files changed

+30
-4
lines changed

src/Connection.php

+9-4
Original file line numberDiff line numberDiff line change
@@ -926,15 +926,20 @@ public function lastInsertId(): int|string
926926
public function transactional(Closure $func): mixed
927927
{
928928
$this->beginTransaction();
929+
930+
$successful = false;
931+
929932
try {
930933
$res = $func($this);
931934
$this->commit();
932935

933-
return $res;
934-
} catch (Throwable $e) {
935-
$this->rollBack();
936+
$successful = true;
936937

937-
throw $e;
938+
return $res;
939+
} finally {
940+
if (! $successful) {
941+
$this->rollBack();
942+
}
938943
}
939944
}
940945

tests/ConnectionTest.php

+21
Original file line numberDiff line numberDiff line change
@@ -623,4 +623,25 @@ public function testDefaultSchemaManagerFactory(): void
623623
$connection = DriverManager::getConnection(['driver' => 'sqlite3', 'memory' => true]);
624624
self::assertInstanceOf(SQLiteSchemaManager::class, $connection->createSchemaManager());
625625
}
626+
627+
public function testItPreservesTheOriginalExceptionOnRollbackFailure(): void
628+
{
629+
$connection = new class (['memory' => true], new Driver\SQLite3\Driver()) extends Connection {
630+
public function rollBack(): void
631+
{
632+
throw new ConnectionException('Rollback exception');
633+
}
634+
};
635+
636+
try {
637+
$connection->transactional(static function (): void {
638+
throw new ConnectionException('Original exception');
639+
});
640+
self::fail('Exception expected'); // @phpstan-ignore deadCode.unreachable
641+
} catch (ConnectionException $e) {
642+
self::assertSame('Rollback exception', $e->getMessage());
643+
self::assertNotNull($e->getPrevious());
644+
self::assertSame('Original exception', $e->getPrevious()->getMessage());
645+
}
646+
}
626647
}

0 commit comments

Comments
 (0)