Skip to content

Commit

Permalink
added Connection::transaction()
Browse files Browse the repository at this point in the history
(cherry picked from commit 07f994a)
  • Loading branch information
dg authored and Jakub-Fajkus committed Feb 9, 2022
1 parent ef9a327 commit 1de72e1
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/Dibi/Connection.php
Original file line number Diff line number Diff line change
Expand Up @@ -402,6 +402,23 @@ public function rollback(string $savepoint = null): void
}


/**
* @return mixed
*/
public function transaction(callable $callback)
{
$this->begin();
try {
$res = $callback();
} catch (\Throwable $e) {
$this->rollback();
throw $e;
}
$this->commit();
return $res;
}


/**
* Result set factory.
*/
Expand Down
1 change: 1 addition & 0 deletions src/Dibi/dibi.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
* @method static void begin(string $savepoint = null)
* @method static void commit(string $savepoint = null)
* @method static void rollback(string $savepoint = null)
* @method static mixed transaction(callable $callback)
* @method static Dibi\Reflection\Database getDatabaseInfo()
* @method static Dibi\Fluent command()
* @method static Dibi\Fluent select(...$args)
Expand Down
21 changes: 21 additions & 0 deletions tests/dibi/Connection.transactions.phpt
Original file line number Diff line number Diff line change
Expand Up @@ -48,3 +48,24 @@ $conn->query('INSERT INTO [products]', [
]);
$conn->commit();
Assert::same(4, (int) $conn->query('SELECT COUNT(*) FROM [products]')->fetchSingle());



Assert::exception(function () use ($conn) {
$conn->transaction(function () use ($conn) {
$conn->query('INSERT INTO [products]', [
'title' => 'Test product',
]);
throw new Exception('my exception');
});
}, \Throwable::class, 'my exception');

Assert::same(4, (int) $conn->query('SELECT COUNT(*) FROM [products]')->fetchSingle());

$conn->transaction(function () use ($conn) {
$conn->query('INSERT INTO [products]', [
'title' => 'Test product',
]);
});

Assert::same(5, (int) $conn->query('SELECT COUNT(*) FROM [products]')->fetchSingle());

0 comments on commit 1de72e1

Please sign in to comment.