Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions src/Connection.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,14 @@
use Artemeon\Database\Schema\Table;
use Artemeon\Database\Schema\TableIndex;
use BackedEnum;
use Closure;
use Generator;
use InvalidArgumentException;
use Override;
use Psr\Log\LoggerInterface;
use RuntimeException;
use Stringable;
use Throwable;

/**
* This class handles all traffic from and to the database and takes care of a correct tx-handling
Expand Down Expand Up @@ -741,6 +743,24 @@ public function rollBack(): void
$this->numberOfOpenTransactions--;
}

#[Override]
public function transactional(Closure $callback): mixed
{
$this->beginTransaction();

try {
$callbackResult = $callback();

$this->commit();
} catch (Throwable $exception) {
$this->rollBack();

throw $exception;
}

return $callbackResult;
}

/**
* @inheritDoc
* @throws ConnectionException
Expand Down
14 changes: 14 additions & 0 deletions src/DoctrineConnectionInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,10 @@

namespace Artemeon\Database;

use Closure;
use Generator;
use Stringable;
use Throwable;

/**
* Interface, which is compatible to the Doctrine DBAL Connection class
Expand Down Expand Up @@ -128,4 +130,16 @@ public function commit(): void;
* Rollback of the current transaction.
*/
public function rollBack(): void;

/**
* Execute a Closure within a transaction.
*
* @template TReturn of mixed
*
* @param Closure():TReturn $callback
*
* @throws Throwable
* @return TReturn
*/
public function transactional(Closure $callback): mixed;
}
7 changes: 7 additions & 0 deletions src/MockConnection.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
use Artemeon\Database\Schema\Table;
use Artemeon\Database\Schema\TableIndex;
use BackedEnum;
use Closure;
use Generator;
use Override;

Expand Down Expand Up @@ -221,6 +222,12 @@ public function transactionRollback(): void
{
}

#[Override]
public function transactional(Closure $callback): mixed
{
return $callback();
}

#[Override]
public function hasDriver(string $class): bool
{
Expand Down
Loading