Skip to content

Commit 44227fe

Browse files
committed
Connection, Context: added transaction()
1 parent 72d54d8 commit 44227fe

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
@@ -64,6 +64,15 @@ public function rollBack(): void
6464
}
6565

6666

67+
/**
68+
* @return mixed
69+
*/
70+
public function transaction(callable $callback)
71+
{
72+
return $this->connection->transaction($callback);
73+
}
74+
75+
6776
public function getInsertId(string $sequence = null): string
6877
{
6978
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+
}, \Throwable::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)