Skip to content

Commit 994e199

Browse files
committed
Connection, Context: added transaction()
1 parent efcac6c commit 994e199

File tree

3 files changed

+38
-0
lines changed

3 files changed

+38
-0
lines changed

src/Database/Connection.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,23 @@ public function rollBack(): void
152152
}
153153

154154

155+
/**
156+
* @return mixed
157+
*/
158+
public function transaction(callable $callback)
159+
{
160+
$this->beginTransaction();
161+
try {
162+
$res = $callback();
163+
} catch (\Throwable $e) {
164+
$this->rollBack();
165+
throw $e;
166+
}
167+
$this->commit();
168+
return $res;
169+
}
170+
171+
155172
/**
156173
* Generates and executes SQL query.
157174
*/

src/Database/Context.php

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,15 @@ public function rollBack(): void
6060
}
6161

6262

63+
/**
64+
* @return mixed
65+
*/
66+
public function transaction(callable $callback)
67+
{
68+
return $this->connection->transaction($callback);
69+
}
70+
71+
6372
public function getInsertId(string $sequence = null): string
6473
{
6574
return $this->connection->getInsertId($sequence);

tests/Database/Context.transaction.phpt

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,18 @@ test(function () use ($context) {
2323
});
2424

2525

26+
test(function () use ($context) {
27+
Assert::exception(function () use ($context) {
28+
$context->transaction(function () use ($context) {
29+
$context->query('DELETE FROM book');
30+
throw new Exception('my exception');
31+
});
32+
}, Exception::class, 'my exception');
33+
34+
Assert::same(3, $context->fetchField('SELECT id FROM book WHERE id = ', 3));
35+
});
36+
37+
2638
test(function () use ($context) {
2739
$context->beginTransaction();
2840
$context->query('DELETE FROM book');

0 commit comments

Comments
 (0)