Skip to content

Commit

Permalink
Run risky code in finally block (doctrine#6543)
Browse files Browse the repository at this point in the history
<!-- Fill in the relevant information below to help triage your pull
request. -->

|      Q       |   A
|------------- | -----------
| Type         | bug
| Fixed issues | doctrine#4846

#### Summary

Let's do the same thing as for ORM in
doctrine/orm#11646

This somehow solves issue we tried to resolve in
doctrine#4846 by providing original
exception in Previous.
  • Loading branch information
simPod authored Oct 11, 2024
1 parent 61446f0 commit c204fe1
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 4 deletions.
13 changes: 9 additions & 4 deletions src/Connection.php
Original file line number Diff line number Diff line change
Expand Up @@ -1278,15 +1278,20 @@ public function lastInsertId($name = null)
public function transactional(Closure $func)
{
$this->beginTransaction();

$successful = false;

try {
$res = $func($this);
$this->commit();

return $res;
} catch (Throwable $e) {
$this->rollBack();
$successful = true;

throw $e;
return $res;
} finally {
if (! $successful) {
$this->rollBack();
}
}
}

Expand Down
21 changes: 21 additions & 0 deletions tests/ConnectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1004,6 +1004,27 @@ public function testLegacySchemaManagerFactory(): void
$connection = DriverManager::getConnection(['driver' => 'sqlite3', 'memory' => true]);
self::assertInstanceOf(SqliteSchemaManager::class, $connection->createSchemaManager());
}

public function testItPreservesTheOriginalExceptionOnRollbackFailure(): void
{
$connection = new class (['memory' => true], new Driver\SQLite3\Driver()) extends Connection {
public function rollBack(): void
{
throw new Exception('Rollback exception');
}
};

try {
$connection->transactional(static function (): void {
throw new Exception('Original exception');
});
self::fail('Exception expected');
} catch (Exception $e) {
self::assertSame('Rollback exception', $e->getMessage());
self::assertNotNull($e->getPrevious());
self::assertSame('Original exception', $e->getPrevious()->getMessage());
}
}
}

interface ConnectDispatchEventListener
Expand Down

0 comments on commit c204fe1

Please sign in to comment.