mirror of
https://github.com/dg/dibi.git
synced 2025-01-17 14:18:25 +01:00
added Connection::transaction()
This commit is contained in:
parent
5fa5acb724
commit
07f994a0b5
@ -402,6 +402,23 @@ class Connection implements IConnection
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @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.
|
||||
*/
|
||||
|
@ -25,6 +25,7 @@ declare(strict_types=1);
|
||||
* @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)
|
||||
|
@ -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());
|
||||
|
Loading…
x
Reference in New Issue
Block a user