File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff 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
You can’t perform that action at this time.
0 commit comments