From 0945254f53f4450905c925e206ad92746c6e978b Mon Sep 17 00:00:00 2001 From: Composite PHP Date: Sat, 13 Jul 2024 14:46:06 +0100 Subject: [PATCH] Add CombinedTransaction::try() --- src/CombinedTransaction.php | 13 +++++++++++++ tests/Table/CombinedTransactionTest.php | 14 ++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/src/CombinedTransaction.php b/src/CombinedTransaction.php index bb8a4a5..bb5a590 100644 --- a/src/CombinedTransaction.php +++ b/src/CombinedTransaction.php @@ -54,6 +54,19 @@ public function delete(AbstractTable $table, AbstractEntity &$entity): void }); } + /** + * @throws Exceptions\DbException + */ + public function try(callable $callback): void + { + try { + $callback(); + } catch (\Throwable $e) { + $this->rollback(); + throw new Exceptions\DbException($e->getMessage(), 500, $e); + } + } + public function rollback(): void { foreach ($this->transactions as $connection) { diff --git a/tests/Table/CombinedTransactionTest.php b/tests/Table/CombinedTransactionTest.php index 1e67a2c..78f3ef2 100644 --- a/tests/Table/CombinedTransactionTest.php +++ b/tests/Table/CombinedTransactionTest.php @@ -130,6 +130,20 @@ public function test_failedDelete(): void $this->assertNotNull($compositeTable->findOne($cEntity->user_id, $cEntity->post_id)); } + public function test_try(): void + { + $compositeTable = new Tables\TestCompositeTable(); + $entity = new Entities\TestCompositeEntity(user_id: mt_rand(1, 1000), post_id: mt_rand(1, 1000), message: 'Bar');; + + try { + $transaction = new CombinedTransaction(); + $transaction->save($compositeTable, $entity); + $transaction->try(fn() => throw new \Exception('test')); + $transaction->commit(); + } catch (DbException) {} + $this->assertNull($compositeTable->findOne($entity->user_id, $entity->post_id)); + } + public function test_lockFailed(): void { $cache = new Helpers\FalseCache();