Skip to content

Commit 71fc800

Browse files
committed
Connection, Context: added transaction()
1 parent efcac6c commit 71fc800

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
@@ -66,6 +66,15 @@ public function getInsertId(string $sequence = null): string
6666
}
6767

6868

69+
/**
70+
* @return mixed
71+
*/
72+
public function transaction(callable $callback)
73+
{
74+
return $this->connection->transaction($callback);
75+
}
76+
77+
6978
/**
7079
* Generates and executes SQL query.
7180
*/

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)