Skip to content

Commit 13479be

Browse files
committed
Add transaction method (unfinished)
1 parent 22b47f9 commit 13479be

1 file changed

Lines changed: 24 additions & 0 deletions

File tree

src/PeachySql.php

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,30 @@ public function __construct(PDO $connection, ?Options $options = null)
2929
$this->options = $options;
3030
}
3131

32+
/**
33+
* Automatically begins a transaction, runs the callback function, and commits
34+
* the transaction on success, or rolls it back if an error occurs.
35+
*
36+
* @template T
37+
* @param (\Closure(static): T) $callback
38+
* @return T
39+
*/
40+
public function transaction(\Closure $callback): mixed
41+
{
42+
// For reference, how similar functionality is implemented in Doctrine and Laravel:
43+
// https://github.com/doctrine/dbal/blob/5.0.x/src/Connection.php#L909
44+
// https://github.com/laravel/framework/blob/12.x/src/Illuminate/Database/Concerns/ManagesTransactions.php#L16
45+
$this->begin();
46+
try {
47+
$result = $callback($this);
48+
$this->commit();
49+
return $result;
50+
} catch (\Throwable $e) {
51+
$this->rollback();
52+
throw $e;
53+
}
54+
}
55+
3256
/**
3357
* Begins a transaction
3458
* @throws SqlException if an error occurs

0 commit comments

Comments
 (0)