File tree Expand file tree Collapse file tree 3 files changed +38
-0
lines changed Expand file tree Collapse file tree 3 files changed +38
-0
lines changed Original file line number Diff line number Diff 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 */
Original file line number Diff line number Diff 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 );
Original file line number Diff line number Diff 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+
2638test (function () use ($ context ) {
2739 $ context ->beginTransaction ();
2840 $ context ->query ('DELETE FROM book ' );
You can’t perform that action at this time.
0 commit comments