Skip to content

Commit

Permalink
Merge branch '3.9.x' into 4.2.x
Browse files Browse the repository at this point in the history
* 3.9.x:
  Run risky code in finally block (doctrine#6543)
  • Loading branch information
derrabus committed Oct 11, 2024
2 parents dadd353 + c204fe1 commit 220aec4
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 @@ -926,15 +926,20 @@ public function lastInsertId(): int|string
public function transactional(Closure $func): mixed
{
$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 @@ -623,4 +623,25 @@ public function testDefaultSchemaManagerFactory(): 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 ConnectionException('Rollback exception');
}
};

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

0 comments on commit 220aec4

Please sign in to comment.