From 1994330b3462ff39acc21d17332e26be2a3be57b Mon Sep 17 00:00:00 2001 From: Jan Skrasek Date: Sat, 14 Nov 2026 20:21:53 +0100 Subject: [PATCH 1/2] Add model rollback and repository state cleanup --- composer.json | 2 +- docs/migrate_6.0.md | 4 + docs/model.md | 18 +++++ docs/unique-constraint.md | 22 +++--- src/Exception/RollbackException.php | 31 ++++++++ src/Mapper/Dbal/DbalMapper.php | 3 +- src/Mapper/Dbal/DbalMapperCoordinator.php | 29 +++++++- src/Mapper/IRollbackableMapper.php | 12 +++ src/Mapper/Memory/ArrayMapper.php | 4 +- src/Model/IModel.php | 6 ++ src/Model/Model.php | 42 +++++++++++ src/Repository/IdentityMap.php | 17 ++++- src/Repository/Repository.php | 45 +++++++++++- .../integration/Model/model.rollback.phpt | 73 +++++++++++++++++++ .../Dbal/DbalMapperCoordinatorTest.phpt | 57 +++++++++++++++ tests/cases/unit/Model/Model.rollback.phpt | 59 +++++++++++++++ .../unit/Repository/IdentityMapTest.phpt | 12 +++ 17 files changed, 412 insertions(+), 24 deletions(-) create mode 100644 src/Exception/RollbackException.php create mode 100644 src/Mapper/IRollbackableMapper.php create mode 100644 tests/cases/integration/Model/model.rollback.phpt create mode 100644 tests/cases/unit/Mapper/Dbal/DbalMapperCoordinatorTest.phpt create mode 100644 tests/cases/unit/Model/Model.rollback.phpt diff --git a/composer.json b/composer.json index 2c0053603..e23393567 100644 --- a/composer.json +++ b/composer.json @@ -24,7 +24,7 @@ "ext-ctype": "*", "nette/caching": "~3.2 || ~3.1.3 || ~4.0.0", "nette/utils": "~3.0 || ~4.0", - "nextras/dbal": "~6.0.0-alpha2", + "nextras/dbal": "dev-main", "phpstan/phpdoc-parser": "^1.33.0 || ^2.0.0" }, "require-dev": { diff --git a/docs/migrate_6.0.md b/docs/migrate_6.0.md index 7c50059ba..08708f29e 100644 --- a/docs/migrate_6.0.md +++ b/docs/migrate_6.0.md @@ -2,6 +2,8 @@ ### BC Breaks +- **`IModel` gained `rollback(): void`.** Custom models must roll back initialized rollback-capable mappers and reset their repository state. `clear()` also discards pending flush notifications and invalidates entities from failed persistence attempts and removals. + - **Relational comparisons with `null` in `ArrayCollection` follow database filtering semantics** - the `<`, `<=`, `>`, and `>=` operators now return `false` when either operand is `null`. Previously, PHP comparisons or property comparators could include entities whose corresponding SQL comparison would exclude them. This affects filtering over nullable properties and comparisons against `null`. - **`IProperty::setRawValue()` must not validate the value** - the method now only stores the passed raw value; it must neither convert it to the runtime representation nor validate it. Both the conversion and any validation are deferred to read time (`getInjectedValue()` / `getRawValue()`). @@ -48,6 +50,8 @@ ### New Features +- **Model rollback and state cleanup.** `Model::rollback()` rolls back initialized mappers and resets their repository state. Custom mappers can implement `IRollbackableMapper`; see [model rollback](model#rollback). + - **Virtual entity properties with PHP 8.4 hooks** - mark a public virtual property with `#[Nextras\Orm\Entity\VirtualEntityProperty]` to register it in Orm metadata without duplicating its type in PHPDoc. It supports entity value access and array export, and is excluded from persistence. Unmarked hooks are not registered. See [entity properties](entity#virtual). - **`Nextras\Orm\Extension` entry point** - a new abstract class that lets bundled or third-party packages hook into the Orm setup. Override any of the methods you need and register the extension: diff --git a/docs/model.md b/docs/model.md index 38ee2f177..37d3ecb1c 100644 --- a/docs/model.md +++ b/docs/model.md @@ -44,6 +44,24 @@ $model->flush(); ``` +#### Rollback + +`Model::rollback()` rolls back unflushed writes in initialized rollback-capable mappers and resets repository state. Loaded entities and entities involved in persistence/removal attempts are invalidated: release those references and obtain fresh entities for subsequent work. + +```php +try { + $model->persist($entity); + $model->flush(); +} catch (\Throwable $e) { + $model->rollback(); + // Release $entity and all other affected entity references. + throw $e; +} +``` + +Rollback resets identity maps, refresh markers, relationship caches, and pending flush notifications. It does not restore old PHP objects to their earlier values. Cleanup is attempted for every initialized repository. If cleanup fails, `Nextras\Orm\Exception\RollbackException` exposes the errors through `getCleanupErrors()`. Discard the model and affected entities after cleanup fails; a Dbal coordinator whose rollback failed cannot be reused. + + #### Refresh In some use cases, it is necessary to refresh the entity data from the storage, where they may have been changed. However, just repeatedly fetching an entity from the repository does not return an updated entity though it may run a new database select query. This is due to the Identity map and Orm data consistency. To solve the refresh need, Orm provides the `Model::refreshAll()` method which will refresh all entities from the storage. diff --git a/docs/unique-constraint.md b/docs/unique-constraint.md index b843ff71b..20955aced 100644 --- a/docs/unique-constraint.md +++ b/docs/unique-constraint.md @@ -1,21 +1,17 @@ ## UniqueConstraintViolationException handling -Quite often you may encounter a race condition when an entry already exists in the database and inserting another one causes a unique constraint failure. Dbal converts this database error into a `UniqueConstraintViolationException`, so you may catch it and mitigate it. - -1) First, try/catch the exception to prevent your app from crashing. -2) Rollback the invalid query on the DB connection. Orm itself on the repository layer does not know about storage implementation; therefore, it's your responsibility to clean up the consequences. -3) Refresh the model to retrieve the current database state. - -In the example below, the persist action may fail because there is already a like for a specific author & article. +A concurrent request can insert a row before your request does. Dbal converts a duplicate-key error into `UniqueConstraintViolationException`, which the application can catch. Use `Model::rollback()` to roll back pending writes and reset repository state: ```php try { - $like = new Like(); - $like->article = $article; - $like->author = $author; - $this->orm->likes->persistAndFlush($like); + $like = new Like(); + $like->article = $article; + $like->author = $author; + $this->orm->persistAndFlush($like); } catch (\Nextras\Dbal\Drivers\Exception\UniqueConstraintViolationException $e) { - $this->orm->likes->getMapper()->rollback(); - $this->orm->refreshAll() + $this->orm->rollback(); + // Obtain fresh entities here, for example to find the already existing like. } ``` + +Release references to loaded entities and entities involved in persistence/removal attempts after rollback. Their state has been invalidated. Discard the model if rollback or state cleanup fails. See [model rollback](model#rollback). diff --git a/src/Exception/RollbackException.php b/src/Exception/RollbackException.php new file mode 100644 index 000000000..4b3399550 --- /dev/null +++ b/src/Exception/RollbackException.php @@ -0,0 +1,31 @@ + */ + private readonly array $cleanupErrors, + Throwable|null $previous = null, + ) + { + parent::__construct('Failed to roll back or reset ORM state.', 0, $previous ?? $cleanupErrors[0]); + } + + + /** + * @return non-empty-list + */ + public function getCleanupErrors(): array + { + return $this->cleanupErrors; + } +} diff --git a/src/Mapper/Dbal/DbalMapper.php b/src/Mapper/Dbal/DbalMapper.php index d1d7d212e..cb13e8e2e 100644 --- a/src/Mapper/Dbal/DbalMapper.php +++ b/src/Mapper/Dbal/DbalMapper.php @@ -26,6 +26,7 @@ use Nextras\Orm\Mapper\Dbal\Conventions\Inflector\SnakeCaseInflector; use Nextras\Orm\Mapper\IMapper; use Nextras\Orm\Mapper\IRelationshipMapper; +use Nextras\Orm\Mapper\IRollbackableMapper; use Nextras\Orm\Repository\IRepository; use Nextras\Orm\StorageReflection\StringHelper; @@ -34,7 +35,7 @@ * @template E of IEntity * @implements IMapper */ -abstract class DbalMapper implements IMapper +abstract class DbalMapper implements IMapper, IRollbackableMapper { /** * Database table name. diff --git a/src/Mapper/Dbal/DbalMapperCoordinator.php b/src/Mapper/Dbal/DbalMapperCoordinator.php index 98b011828..9aa5b00f0 100644 --- a/src/Mapper/Dbal/DbalMapperCoordinator.php +++ b/src/Mapper/Dbal/DbalMapperCoordinator.php @@ -4,12 +4,16 @@ use Nextras\Dbal\IConnection; +use Nextras\Orm\Exception\InvalidStateException; +use Throwable; class DbalMapperCoordinator { private bool $transactionActive = false; + private Throwable|null $rollbackFailure = null; + public function __construct( private readonly IConnection $connection, @@ -20,6 +24,7 @@ public function __construct( public function beginTransaction(): void { + $this->checkUsable(); if (!$this->transactionActive) { $this->connection->beginTransaction(); $this->transactionActive = true; @@ -29,6 +34,7 @@ public function beginTransaction(): void public function flush(): void { + $this->checkUsable(); if ($this->transactionActive) { $this->connection->commitTransaction(); $this->transactionActive = false; @@ -38,9 +44,28 @@ public function flush(): void public function rollback(): void { + $this->checkUsable(); if ($this->transactionActive) { - $this->connection->rollbackTransaction(); - $this->transactionActive = false; + try { + $this->connection->rollbackTransaction(); + } catch (Throwable $e) { + $this->rollbackFailure = $e; + throw $e; + } finally { + $this->transactionActive = false; + } + } + } + + + private function checkUsable(): void + { + if ($this->rollbackFailure !== null) { + throw new InvalidStateException( + 'The transaction coordinator cannot be reused after rollback failed.', + 0, + $this->rollbackFailure, + ); } } } diff --git a/src/Mapper/IRollbackableMapper.php b/src/Mapper/IRollbackableMapper.php new file mode 100644 index 000000000..5e80df707 --- /dev/null +++ b/src/Mapper/IRollbackableMapper.php @@ -0,0 +1,12 @@ + */ -abstract class ArrayMapper implements IMapper +abstract class ArrayMapper implements IMapper, IRollbackableMapper { /** @var array|null */ protected array|null $data = null; @@ -198,6 +199,7 @@ public function flush(): void public function rollback(): void { $this->data = null; + $this->relationshipData = []; } diff --git a/src/Model/IModel.php b/src/Model/IModel.php index 4260f95a8..2d496cbf8 100644 --- a/src/Model/IModel.php +++ b/src/Model/IModel.php @@ -91,6 +91,12 @@ public function removeAndFlush(IEntity $entity, bool $withCascade = true): IEnti */ public function flush(): void; + /** + * Rolls back unflushed mapper writes and invalidates loaded and affected entities and pending flush notifications. + * Discard the model if rollback or state cleanup fails. + */ + public function rollback(): void; + /** * Clears repository identity map and other possible caches. * Make sure that all references to already used entites are released, diff --git a/src/Model/Model.php b/src/Model/Model.php index 95d8c8932..a5e1f4caf 100644 --- a/src/Model/Model.php +++ b/src/Model/Model.php @@ -6,11 +6,15 @@ use Nette\SmartObject; use Nextras\Orm\Entity\IEntity; use Nextras\Orm\Exception\InvalidArgumentException; +use Nextras\Orm\Exception\NotSupportedException; +use Nextras\Orm\Exception\RollbackException; +use Nextras\Orm\Mapper\IRollbackableMapper; use Nextras\Orm\Relationships\IRelationshipCollection; use Nextras\Orm\Relationships\IRelationshipContainer; use Nextras\Orm\Repository\IRepository; use Nextras\Orm\Repository\PersistenceHelper; use Nextras\Orm\Repository\PersistenceMode; +use Throwable; use function array_merge; use function is_string; @@ -122,6 +126,44 @@ public function flush(): void } + public function rollback(): void + { + $errors = []; + foreach ($this->repositoryLoader->getInitializedRepositories() as $repository) { + try { + $mapper = $repository->getMapper(); + if (!$mapper instanceof IRollbackableMapper) { + throw new NotSupportedException('Mapper ' . $mapper::class . ' does not support rollback.'); + } + $mapper->rollback(); + } catch (Throwable $e) { + $errors[] = $e; + } + } + $errors = array_merge($errors, $this->resetRepositories()); + if ($errors !== []) { + throw new RollbackException($errors); + } + } + + + /** + * @return list + */ + private function resetRepositories(): array + { + $errors = []; + foreach ($this->repositoryLoader->getInitializedRepositories() as $repository) { + try { + $repository->doClear(); + } catch (Throwable $e) { + $errors[] = $e; + } + } + return $errors; + } + + public function clear(): void { foreach ($this->repositoryLoader->getInitializedRepositories() as $repository) { diff --git a/src/Repository/IdentityMap.php b/src/Repository/IdentityMap.php index d5bb7c148..561e0cc41 100644 --- a/src/Repository/IdentityMap.php +++ b/src/Repository/IdentityMap.php @@ -13,7 +13,9 @@ use Nextras\Orm\Entity\IEntity; use Nextras\Orm\Entity\IEntityHasPreloadContainer; use Nextras\Orm\Exception\InvalidArgumentException; +use Nextras\Orm\Exception\RollbackException; use ReflectionClass; +use Throwable; /** @@ -154,14 +156,21 @@ public function check(IEntity $entity): void public function destroyAllEntities(): void { - foreach ($this->entities as $entityRef) { - if ($entityRef !== false && ($entity = $entityRef->get()) !== null) { + $entities = $this->getAll(); + $this->entities = []; + $this->entitiesForRefresh = []; + $errors = []; + foreach ($entities as $entity) { + try { $this->repository->detach($entity); $entity->onFree(); + } catch (Throwable $e) { + $errors[] = $e; } } - - $this->entities = []; + if ($errors !== []) { + throw new RollbackException($errors); + } } diff --git a/src/Repository/Repository.php b/src/Repository/Repository.php index e562b3fd2..40588bf03 100644 --- a/src/Repository/Repository.php +++ b/src/Repository/Repository.php @@ -35,10 +35,12 @@ use Nextras\Orm\Exception\MemberAccessException; use Nextras\Orm\Exception\NoResultException; use Nextras\Orm\Exception\NotImplementedException; +use Nextras\Orm\Exception\RollbackException; use Nextras\Orm\Mapper\IMapper; use Nextras\Orm\Model\IModel; use Nextras\Orm\Model\MetadataStorage; use ReflectionClass; +use Throwable; use function sort; @@ -90,6 +92,9 @@ abstract class Repository implements IRepository /** @var array{list, list} */ private array $entitiesToFlush = [[], []]; + /** @var list Persistence and removal attempts retained until the transaction completes. */ + private array $entitiesToRollback = []; + /** @var array Collection functions cache */ private array $collectionFunctions = []; @@ -425,14 +430,48 @@ public function doFlush(): array $this->onFlush($this->entitiesToFlush[0], $this->entitiesToFlush[1]); $entities = $this->entitiesToFlush; $this->entitiesToFlush = [[], []]; + $this->entitiesToRollback = []; return $entities; } public function doClear(): void { - $this->identityMap->destroyAllEntities(); - $this->mapper->clearCache(); + $managedIds = []; + foreach ($this->identityMap->getAll() as $entity) { + $managedIds[spl_object_id($entity)] = true; + } + $pending = array_merge($this->entitiesToRollback, $this->entitiesToFlush[0], $this->entitiesToFlush[1]); + $this->entitiesToFlush = [[], []]; + $this->entitiesToRollback = []; + $this->collectionFunctions = []; + $errors = []; + try { + $this->identityMap->destroyAllEntities(); + } catch (Throwable $e) { + $errors[] = $e; + } + foreach ($pending as $entity) { + $id = spl_object_id($entity); + if (isset($managedIds[$id]) || ($entity->isAttached() && $entity->getRepository() !== $this)) { + continue; + } + $managedIds[$id] = true; + try { + $this->detach($entity); + $entity->onFree(); + } catch (Throwable $e) { + $errors[] = $e; + } + } + try { + $this->mapper->clearCache(); + } catch (Throwable $e) { + $errors[] = $e; + } + if ($errors !== []) { + throw new RollbackException($errors); + } } @@ -485,6 +524,7 @@ public function doRefreshAll(bool $allowOverwrite): void public function onBeforePersist(IEntity $entity): void { + $this->entitiesToRollback[] = $entity; $entity->onBeforePersist(); foreach ($this->onBeforePersist as $handler) { $handler($entity); @@ -539,6 +579,7 @@ public function onAfterUpdate(IEntity $entity): void public function onBeforeRemove(IEntity $entity): void { + $this->entitiesToRollback[] = $entity; $entity->onBeforeRemove(); foreach ($this->onBeforeRemove as $handler) { $handler($entity); diff --git a/tests/cases/integration/Model/model.rollback.phpt b/tests/cases/integration/Model/model.rollback.phpt new file mode 100644 index 000000000..82402bb90 --- /dev/null +++ b/tests/cases/integration/Model/model.rollback.phpt @@ -0,0 +1,73 @@ +name = 'Uncommitted'; + $this->orm->persist($author); + $id = $author->id; + $publisher = $this->orm->publishers->getByIdChecked(1); + $originalName = $publisher->name; + $publisher->name = 'Uncommitted publisher'; + $this->orm->persist($publisher); + $this->orm->rollback(); + Assert::false($author->isAttached()); + Assert::false($author->isPersisted()); + Assert::false($publisher->isAttached()); + Assert::null($this->orm->authors->getById($id)); + Assert::same($originalName, $this->orm->publishers->getByIdChecked(1)->name); + + $notifications = []; + $this->orm->onFlush[] = static function (array $persisted) use (&$notifications): void { + $notifications[] = count($persisted); + }; + $this->orm->flush(); + Assert::same([0], $notifications); + + $fresh = new Author(); + $fresh->name = 'Committed'; + $this->orm->persistAndFlush($fresh); + Assert::true($fresh->isPersisted()); + } + + + public function testRollbackInvalidatesRemovedEntityAndRestoresRelationship(): void + { + $book = $this->orm->books->getByIdChecked(1); + $tag = $book->tags->toCollection()->fetchChecked(); + $tagId = $tag->id; + $book->tags->remove($tag); + $this->orm->persist($book); + $this->orm->remove($book, false); + $this->orm->rollback(); + Assert::false($book->isAttached()); + Assert::false($book->isPersisted()); + $fresh = $this->orm->books->getByIdChecked(1); + Assert::notSame($book, $fresh); + Assert::type(IEntity::class, $fresh->tags->toCollection()->getBy(['id' => $tagId])); + } +} + + +(new ModelRollbackTest())->run(); diff --git a/tests/cases/unit/Mapper/Dbal/DbalMapperCoordinatorTest.phpt b/tests/cases/unit/Mapper/Dbal/DbalMapperCoordinatorTest.phpt new file mode 100644 index 000000000..c48b030e3 --- /dev/null +++ b/tests/cases/unit/Mapper/Dbal/DbalMapperCoordinatorTest.phpt @@ -0,0 +1,57 @@ +shouldReceive('beginTransaction')->once(); + $connection->shouldReceive('rollbackTransaction')->once(); + $coordinator = new DbalMapperCoordinator($connection); + Assert::noError(static function () use ($coordinator): void { + $coordinator->beginTransaction(); + $coordinator->beginTransaction(); + $coordinator->rollback(); + $coordinator->rollback(); + }); + } + + + public function testFailedRollbackPreventsCoordinatorReuse(): void + { + $connection = Mockery::mock(IConnection::class); + $connection->shouldReceive('beginTransaction')->once(); + $connection->shouldReceive('rollbackTransaction')->once()->andThrow(new RuntimeException('Rollback failed')); + $coordinator = new DbalMapperCoordinator($connection); + $coordinator->beginTransaction(); + Assert::exception(fn() => $coordinator->rollback(), RuntimeException::class); + Assert::exception(fn() => $coordinator->beginTransaction(), InvalidStateException::class); + } + + + protected function tearDown(): void + { + Mockery::close(); + } +} + + +(new DbalMapperCoordinatorTest())->run(); diff --git a/tests/cases/unit/Model/Model.rollback.phpt b/tests/cases/unit/Model/Model.rollback.phpt new file mode 100644 index 000000000..18f427a16 --- /dev/null +++ b/tests/cases/unit/Model/Model.rollback.phpt @@ -0,0 +1,59 @@ +shouldReceive('rollback')->once()->andThrow($failure); + $second = Mockery::mock(IMapper::class, IRollbackableMapper::class); + $second->shouldReceive('rollback')->once(); + $firstRepository = Mockery::mock(IRepository::class); + $firstRepository->shouldReceive('getMapper')->once()->andReturn($first); + $firstRepository->shouldReceive('doClear')->once()->andThrow($resetFailure); + $secondRepository = Mockery::mock(IRepository::class); + $secondRepository->shouldReceive('getMapper')->once()->andReturn($second); + $secondRepository->shouldReceive('doClear')->once(); + $loader = Mockery::mock(IRepositoryLoader::class); + $loader->shouldReceive('getInitializedRepositories')->twice()->andReturn([$firstRepository, $secondRepository]); + $model = new Model($loader, Mockery::mock(MetadataStorage::class)); + $exception = Assert::exception(fn() => $model->rollback(), RollbackException::class); + Assert::type(RollbackException::class, $exception); + Assert::same($failure, $exception->getPrevious()); + Assert::same([$failure, $resetFailure], $exception->getCleanupErrors()); + } + + + protected function tearDown(): void + { + Mockery::close(); + } +} + + +(new ModelRollbackTest())->run(); diff --git a/tests/cases/unit/Repository/IdentityMapTest.phpt b/tests/cases/unit/Repository/IdentityMapTest.phpt index cfc854aa5..711b41b16 100644 --- a/tests/cases/unit/Repository/IdentityMapTest.phpt +++ b/tests/cases/unit/Repository/IdentityMapTest.phpt @@ -33,6 +33,18 @@ class IdentityMapTest extends TestCase $map->check($this->e(Book::class)); }, InvalidArgumentException::class, "Entity 'NextrasTests\\Orm\\Book' is not accepted by 'Mockery_0_Nextras_Orm_Repository_IRepository' repository."); } + + + public function testClearResetsRefreshMarkers(): void + { + $repository = Mockery::mock(IRepository::class); + $map = new IdentityMap($repository); + $entity = $this->e(Author::class, ['id' => 1]); + $map->markForRefresh($entity); + Assert::true($map->isMarkedForRefresh($entity)); + $map->destroyAllEntities(); + Assert::false($map->isMarkedForRefresh($entity)); + } } From f17a162296c47dc786e32fce9772fcedbb2bf67b Mon Sep 17 00:00:00 2001 From: Jan Skrasek Date: Sat, 14 Nov 2026 20:23:11 +0100 Subject: [PATCH 2/2] Add single-connection model transaction callbacks --- docs/migrate_6.0.md | 6 +- docs/model.md | 26 ++- docs/unique-constraint.md | 19 +- src/Bridges/NetteDI/DiRepositoryLoader.php | 12 ++ src/Mapper/Dbal/DbalMapper.php | 15 +- src/Mapper/Dbal/DbalMapperCoordinator.php | 42 +++- src/Mapper/ITransactionCoordinator.php | 16 ++ src/Mapper/ITransactionalMapper.php | 13 ++ src/Model/IModel.php | 14 +- src/Model/IRepositoryLoader.php | 7 + src/Model/Model.php | 128 ++++++++++-- src/Model/SimpleRepositoryLoader.php | 8 + src/Repository/IRepository.php | 8 +- src/Repository/Repository.php | 12 +- .../Model/model.transactional.phpt | 195 ++++++++++++++++++ .../Dbal/DbalMapperCoordinatorTest.phpt | 35 +++- .../cases/unit/Model/Model.transactions.phpt | 115 +++++++++++ 17 files changed, 626 insertions(+), 45 deletions(-) create mode 100644 src/Mapper/ITransactionCoordinator.php create mode 100644 src/Mapper/ITransactionalMapper.php create mode 100644 tests/cases/integration/Model/model.transactional.phpt create mode 100644 tests/cases/unit/Model/Model.transactions.phpt diff --git a/docs/migrate_6.0.md b/docs/migrate_6.0.md index 08708f29e..890d182e6 100644 --- a/docs/migrate_6.0.md +++ b/docs/migrate_6.0.md @@ -2,7 +2,9 @@ ### BC Breaks -- **`IModel` gained `rollback(): void`.** Custom models must roll back initialized rollback-capable mappers and reset their repository state. `clear()` also discards pending flush notifications and invalidates entities from failed persistence attempts and removals. +- **`IModel` gained `rollback()` and `transactional(callable $callback): mixed`.** Custom model implementations must provide these methods. See [model transactions](model#transactions-and-rollback) for their scope and failure semantics. +- **`IRepositoryLoader` gained `getRepositories(): array`.** It must initialize and return every repository. Transaction callbacks use it to validate the whole model before starting work; existing loading remains lazy for the other model APIs. +- **`IRepository::doFlush()` gained `bool $keepRollbackState = false`, and `doFinalizeTransaction(): void` was added.** Custom repository implementations must retain rollback-relevant entity references when requested and release them after a successful storage commit. `clear()` now also discards pending flush notifications and invalidates entities from failed persistence attempts and removals. - **Relational comparisons with `null` in `ArrayCollection` follow database filtering semantics** - the `<`, `<=`, `>`, and `>=` operators now return `false` when either operand is `null`. Previously, PHP comparisons or property comparators could include entities whose corresponding SQL comparison would exclude them. This affects filtering over nullable properties and comparisons against `null`. @@ -50,7 +52,7 @@ ### New Features -- **Model rollback and state cleanup.** `Model::rollback()` rolls back initialized mappers and resets their repository state. Custom mappers can implement `IRollbackableMapper`; see [model rollback](model#rollback). +- **Model transaction callbacks and rollback.** `Model::transactional()` runs one callback, flushes, commits, and resets repository state after failure. Initially it supports one shared transaction coordinator and rejects nested model scopes. `Model::rollback()` rolls back initialized rollback-capable mappers and resets their repository state. Custom mappers can implement `IRollbackableMapper` and `ITransactionalMapper`; see [model transactions](model#transactions-and-rollback). - **Virtual entity properties with PHP 8.4 hooks** - mark a public virtual property with `#[Nextras\Orm\Entity\VirtualEntityProperty]` to register it in Orm metadata without duplicating its type in PHPDoc. It supports entity value access and array export, and is excluded from persistence. Unmarked hooks are not registered. See [entity properties](entity#virtual). diff --git a/docs/model.md b/docs/model.md index 37d3ecb1c..cbdfcc478 100644 --- a/docs/model.md +++ b/docs/model.md @@ -44,9 +44,27 @@ $model->flush(); ``` -#### Rollback +#### Transactions and rollback -`Model::rollback()` rolls back unflushed writes in initialized rollback-capable mappers and resets repository state. Loaded entities and entities involved in persistence/removal attempts are invalidated: release those references and obtain fresh entities for subsequent work. +`Model::transactional()` runs a callback once in a transaction, flushes its writes, and commits before returning the callback result. The transaction starts before the callback, including its reads. Call `persist()` explicitly for each changed entity as usual. + +```php +$userId = 123; +$result = $model->transactional(function ($model) use ($userId) { + $user = $model->users->getByIdChecked($userId); + $user->isEmailSubscribed = false; + $model->persist($user); + return $user->id; +}); +``` + +This API initializes every repository to verify that all mappers support transaction callbacks and share one transaction coordinator. Dbal mappers on the same connection must use the same `DbalMapperCoordinator` instance. Nested model transaction callbacks, an existing connection transaction, and unflushed writes from before the callback are rejected before the callback runs. Array/file mappers support rollback but do not support transaction callbacks. + +Calling `flush()` or `persistAndFlush()` inside the callback does not commit the transaction. The outer scope remains responsible for commit. Existing persistence and flush events still run before the final commit; do not use them as confirmation of a successful commit. Load entities inside the callback when their reads must belong to the transaction; already cached entities are not automatically reloaded. + +If the callback, persistence, flush, or commit throws, the transaction is rolled back and repository state is reset. Loaded entities and entities involved in persistence/removal attempts are invalidated: release those references and obtain fresh entities for subsequent work. A persistence or flush failure also aborts the scope when the callback catches that failure. No automatic retries are performed. Catch errors outside `transactional()`. + +For work performed with the existing `persist()` / `flush()` API, `Model::rollback()` rolls back the initialized mappers and resets their repository state: ```php try { @@ -59,7 +77,9 @@ try { } ``` -Rollback resets identity maps, refresh markers, relationship caches, and pending flush notifications. It does not restore old PHP objects to their earlier values. Cleanup is attempted for every initialized repository. If cleanup fails, `Nextras\Orm\Exception\RollbackException` exposes the errors through `getCleanupErrors()`. Discard the model and affected entities after cleanup fails; a Dbal coordinator whose rollback failed cannot be reused. +Rollback resets identity maps, refresh markers, relationship caches, and pending flush notifications, including failed writes and removed entities. It does not restore old PHP objects to their earlier values. Calling `rollback()` inside a transaction callback is rejected; throw an exception to abort the scope instead. + +Rollback and reset attempt cleanup for every initialized repository. If cleanup fails, `Nextras\Orm\Exception\RollbackException` exposes the cleanup failures through `getCleanupErrors()` and retains the original transaction failure as its previous exception when available. Discard the model and affected entities after cleanup fails. A Dbal transaction rollback failure retains DBAL's `TransactionRollbackException`, and its coordinator cannot be reused. #### Refresh diff --git a/docs/unique-constraint.md b/docs/unique-constraint.md index 20955aced..47f598d20 100644 --- a/docs/unique-constraint.md +++ b/docs/unique-constraint.md @@ -1,17 +1,22 @@ ## UniqueConstraintViolationException handling -A concurrent request can insert a row before your request does. Dbal converts a duplicate-key error into `UniqueConstraintViolationException`, which the application can catch. Use `Model::rollback()` to roll back pending writes and reset repository state: +A concurrent request can insert a row before your request does. Dbal converts a duplicate-key error into `UniqueConstraintViolationException`, which the application can catch. + +Use `Model::transactional()` to roll back the failed operation and reset repository state. Create and load participating entities inside the callback, then catch the error outside it: ```php try { - $like = new Like(); - $like->article = $article; - $like->author = $author; - $this->orm->persistAndFlush($like); + $this->orm->transactional(function ($orm) use ($authorId, $articleId) { + $like = new Like(); + $like->article = $orm->articles->getByIdChecked($articleId); + $like->author = $orm->authors->getByIdChecked($authorId); + $orm->persist($like); + }); } catch (\Nextras\Dbal\Drivers\Exception\UniqueConstraintViolationException $e) { - $this->orm->rollback(); // Obtain fresh entities here, for example to find the already existing like. } ``` -Release references to loaded entities and entities involved in persistence/removal attempts after rollback. Their state has been invalidated. Discard the model if rollback or state cleanup fails. See [model rollback](model#rollback). +After failure, release references to entities loaded or involved in persistence/removal attempts: their state has been invalidated. The callback is executed once; unique constraint violations are not retried automatically. + +If you use `persistAndFlush()` directly, call `Model::rollback()` in the error handler to roll back the pending writes and reset repository state. Discard the model if rollback or state cleanup fails. See [model transactions](model#transactions-and-rollback). diff --git a/src/Bridges/NetteDI/DiRepositoryLoader.php b/src/Bridges/NetteDI/DiRepositoryLoader.php index 888eb5776..6576f9eea 100644 --- a/src/Bridges/NetteDI/DiRepositoryLoader.php +++ b/src/Bridges/NetteDI/DiRepositoryLoader.php @@ -74,6 +74,18 @@ public function getRepositoryClassNameForEntity(string $entityClassName): string } + #[\Override] + #[\NoDiscard] + public function getRepositories(): array + { + $repositories = []; + foreach ($this->repositoryClassNameToDiNameMap as $diName) { + $repositories[] = $this->container->getService($diName); + } + return $repositories; + } + + #[\Override] #[\NoDiscard] public function getInitializedRepositories(): array diff --git a/src/Mapper/Dbal/DbalMapper.php b/src/Mapper/Dbal/DbalMapper.php index cb13e8e2e..82bc13ba8 100644 --- a/src/Mapper/Dbal/DbalMapper.php +++ b/src/Mapper/Dbal/DbalMapper.php @@ -26,7 +26,8 @@ use Nextras\Orm\Mapper\Dbal\Conventions\Inflector\SnakeCaseInflector; use Nextras\Orm\Mapper\IMapper; use Nextras\Orm\Mapper\IRelationshipMapper; -use Nextras\Orm\Mapper\IRollbackableMapper; +use Nextras\Orm\Mapper\ITransactionalMapper; +use Nextras\Orm\Mapper\ITransactionCoordinator; use Nextras\Orm\Repository\IRepository; use Nextras\Orm\StorageReflection\StringHelper; @@ -35,7 +36,7 @@ * @template E of IEntity * @implements IMapper */ -abstract class DbalMapper implements IMapper, IRollbackableMapper +abstract class DbalMapper implements IMapper, ITransactionalMapper { /** * Database table name. @@ -63,6 +64,9 @@ public function __construct( Cache $cache, ) { + if ($mapperCoordinator->getConnection() !== $connection) { + throw new InvalidArgumentException('Mapper and transaction coordinator must use the same connection.'); + } $key = md5(Json::encode($connection->getConfig())); $this->cache = $cache->derive('orm.mapper.' . $key); } @@ -532,6 +536,13 @@ public function flush(): void } + #[\NoDiscard] + public function getTransactionCoordinator(): ITransactionCoordinator + { + return $this->mapperCoordinator; + } + + public function beginTransaction(): void { $this->mapperCoordinator->beginTransaction(); diff --git a/src/Mapper/Dbal/DbalMapperCoordinator.php b/src/Mapper/Dbal/DbalMapperCoordinator.php index 9aa5b00f0..ef33584e7 100644 --- a/src/Mapper/Dbal/DbalMapperCoordinator.php +++ b/src/Mapper/Dbal/DbalMapperCoordinator.php @@ -3,15 +3,19 @@ namespace Nextras\Orm\Mapper\Dbal; +use Nextras\Dbal\Exception\TransactionRollbackException; use Nextras\Dbal\IConnection; use Nextras\Orm\Exception\InvalidStateException; +use Nextras\Orm\Mapper\ITransactionCoordinator; use Throwable; -class DbalMapperCoordinator +class DbalMapperCoordinator implements ITransactionCoordinator { private bool $transactionActive = false; + private bool $managedTransaction = false; + private Throwable|null $rollbackFailure = null; @@ -22,6 +26,13 @@ public function __construct( } + #[\NoDiscard] + public function getConnection(): IConnection + { + return $this->connection; + } + + public function beginTransaction(): void { $this->checkUsable(); @@ -35,7 +46,7 @@ public function beginTransaction(): void public function flush(): void { $this->checkUsable(); - if ($this->transactionActive) { + if ($this->transactionActive && !$this->managedTransaction) { $this->connection->commitTransaction(); $this->transactionActive = false; } @@ -45,6 +56,9 @@ public function flush(): void public function rollback(): void { $this->checkUsable(); + if ($this->managedTransaction) { + throw new InvalidStateException('Cannot roll back a mapper inside Model::transactional(). Throw an exception instead.'); + } if ($this->transactionActive) { try { $this->connection->rollbackTransaction(); @@ -58,6 +72,30 @@ public function rollback(): void } + public function transactional(callable $callback): mixed + { + $this->checkUsable(); + $this->connection->connect(); + if ($this->transactionActive || $this->managedTransaction || $this->connection->getTransactionNestedIndex() !== 0) { + throw new InvalidStateException('Model::transactional() requires a connection without an active transaction.'); + } + + $this->managedTransaction = true; + try { + return $this->connection->transactional(function () use ($callback) { + $this->transactionActive = true; + return $callback(); + }); + } catch (TransactionRollbackException $e) { + $this->rollbackFailure = $e; + throw $e; + } finally { + $this->transactionActive = false; + $this->managedTransaction = false; + } + } + + private function checkUsable(): void { if ($this->rollbackFailure !== null) { diff --git a/src/Mapper/ITransactionCoordinator.php b/src/Mapper/ITransactionCoordinator.php new file mode 100644 index 000000000..3e2876e0c --- /dev/null +++ b/src/Mapper/ITransactionCoordinator.php @@ -0,0 +1,16 @@ +> + */ + #[\NoDiscard] + public function getRepositories(): array; + /** * Returns list of loaded (already initialized) repositories. * @return list> diff --git a/src/Model/Model.php b/src/Model/Model.php index a5e1f4caf..ca4c1f08c 100644 --- a/src/Model/Model.php +++ b/src/Model/Model.php @@ -6,9 +6,11 @@ use Nette\SmartObject; use Nextras\Orm\Entity\IEntity; use Nextras\Orm\Exception\InvalidArgumentException; +use Nextras\Orm\Exception\InvalidStateException; use Nextras\Orm\Exception\NotSupportedException; use Nextras\Orm\Exception\RollbackException; use Nextras\Orm\Mapper\IRollbackableMapper; +use Nextras\Orm\Mapper\ITransactionalMapper; use Nextras\Orm\Relationships\IRelationshipCollection; use Nextras\Orm\Relationships\IRelationshipContainer; use Nextras\Orm\Repository\IRepository; @@ -26,6 +28,10 @@ class Model implements IModel /** @var list */ public array $onFlush = []; + private bool $transactionActive = false; + + private Throwable|null $transactionFailure = null; + public function __construct( private readonly IRepositoryLoader $repositoryLoader, @@ -114,24 +120,46 @@ public function removeAndFlush(IEntity $entity, bool $withCascade = true): IEnti public function flush(): void { - $allPersisted = []; - $allRemoved = []; - foreach ($this->repositoryLoader->getInitializedRepositories() as $repository) { - [$persisted, $removed] = $repository->doFlush(); - $allPersisted = array_merge($allPersisted, $persisted); - $allRemoved = array_merge($allRemoved, $removed); + if ($this->transactionFailure !== null) { + throw new InvalidStateException('The transaction has already failed.', 0, $this->transactionFailure); } + try { + $allPersisted = []; + $allRemoved = []; + foreach ($this->repositoryLoader->getInitializedRepositories() as $repository) { + [$persisted, $removed] = $repository->doFlush($this->transactionActive); + $allPersisted = array_merge($allPersisted, $persisted); + $allRemoved = array_merge($allRemoved, $removed); + } - $this->onFlush($allPersisted, $allRemoved); + $this->onFlush($allPersisted, $allRemoved); + + } catch (Throwable $e) { + if ($this->transactionActive) { + $this->transactionFailure = $e; + } + throw $e; + } } public function rollback(): void { + if ($this->transactionActive) { + throw new InvalidStateException('Cannot call rollback() inside transactional(). Throw an exception instead.'); + } $errors = []; + $participants = []; foreach ($this->repositoryLoader->getInitializedRepositories() as $repository) { try { $mapper = $repository->getMapper(); + if ($mapper instanceof ITransactionalMapper) { + $id = spl_object_id($mapper->getTransactionCoordinator()); + if (isset($participants[$id])) { + continue; + } + $participants[$id] = true; + } if (!$mapper instanceof IRollbackableMapper) { throw new NotSupportedException('Mapper ' . $mapper::class . ' does not support rollback.'); } @@ -147,6 +175,58 @@ public function rollback(): void } + public function transactional(callable $callback): mixed + { + if ($this->transactionActive) { + throw new InvalidStateException('Nested Model::transactional() calls are not supported.'); + } + $coordinator = null; + foreach ($this->repositoryLoader->getRepositories() as $repository) { + $mapper = $repository->getMapper(); + if (!$mapper instanceof ITransactionalMapper) { + throw new NotSupportedException('Mapper ' . $mapper::class . ' does not support transaction callbacks.'); + } + $participant = $mapper->getTransactionCoordinator(); + if ($coordinator !== null && $participant !== $coordinator) { + throw new NotSupportedException('Model::transactional() requires all mappers to share one transaction coordinator.'); + } + $coordinator = $participant; + } + if ($coordinator === null) { + throw new NotSupportedException('Model::transactional() requires at least one transactional mapper.'); + } + + $this->transactionActive = true; + $started = false; + try { + $result = $coordinator->transactional(function () use ($callback, &$started) { + $started = true; + $result = $callback($this); + if ($this->transactionFailure !== null) { + throw $this->transactionFailure; + } + $this->flush(); + return $result; + }); + } catch (Throwable $e) { + if ($started) { + $errors = $this->resetRepositories(); + if ($errors !== []) { + throw new RollbackException($errors, $e); + } + } + throw $e; + } finally { + $this->transactionActive = false; + $this->transactionFailure = null; + } + foreach ($this->repositoryLoader->getInitializedRepositories() as $completedRepository) { + $completedRepository->doFinalizeTransaction(); + } + return $result; + } + + /** * @return list */ @@ -193,20 +273,30 @@ public function &__get(string $name): IRepository protected function processPersist(PersistenceMode $mode, IEntity $entity, bool $withCascade): void { - [$queuePersist, $queueRemove] = PersistenceHelper::getCascadeQueue($entity, $mode, $this, $withCascade); - foreach ($queuePersist as $object) { - if ($object instanceof IEntity) { + if ($this->transactionFailure !== null) { + throw new InvalidStateException('The transaction has already failed.', 0, $this->transactionFailure); + } + try { + [$queuePersist, $queueRemove] = PersistenceHelper::getCascadeQueue($entity, $mode, $this, $withCascade); + foreach ($queuePersist as $object) { + if ($object instanceof IEntity) { + $repository = $this->getRepositoryForEntity($object); + $repository->doPersist($object); + } elseif ($object instanceof IRelationshipCollection) { + $object->doPersist(); + } elseif ($object instanceof IRelationshipContainer) { + $object->doPersist(); + } + } + foreach ($queueRemove as $object) { $repository = $this->getRepositoryForEntity($object); - $repository->doPersist($object); - } elseif ($object instanceof IRelationshipCollection) { - $object->doPersist(); - } elseif ($object instanceof IRelationshipContainer) { - $object->doPersist(); + $repository->doRemove($object); } - } - foreach ($queueRemove as $object) { - $repository = $this->getRepositoryForEntity($object); - $repository->doRemove($object); + } catch (Throwable $e) { + if ($this->transactionActive) { + $this->transactionFailure = $e; + } + throw $e; } } } diff --git a/src/Model/SimpleRepositoryLoader.php b/src/Model/SimpleRepositoryLoader.php index bd2d8c77a..a5ac4a500 100644 --- a/src/Model/SimpleRepositoryLoader.php +++ b/src/Model/SimpleRepositoryLoader.php @@ -95,6 +95,14 @@ public function getRepositoryClassNameForEntity(string $entityClassName): string } + #[\Override] + #[\NoDiscard] + public function getRepositories(): array + { + return array_values($this->repositories); + } + + #[\Override] #[\NoDiscard] public function getInitializedRepositories(): array diff --git a/src/Repository/IRepository.php b/src/Repository/IRepository.php index dbc3f597e..35c9c5a4d 100644 --- a/src/Repository/IRepository.php +++ b/src/Repository/IRepository.php @@ -234,7 +234,13 @@ public function doRemove(IEntity $entity): void; * @ignore * @return array{list, list} array of all persisted & removed entities */ - public function doFlush(): array; + public function doFlush(bool $keepRollbackState = false): array; + + /** + * Releases rollback-only entity references after a successful storage commit. + * @internal + */ + public function doFinalizeTransaction(): void; /** * DO NOT CALL THIS METHOD DIRECTLY. diff --git a/src/Repository/Repository.php b/src/Repository/Repository.php index 40588bf03..0a8a15b52 100644 --- a/src/Repository/Repository.php +++ b/src/Repository/Repository.php @@ -424,17 +424,25 @@ public function removeAndFlush(IEntity $entity, bool $withCascade = true): IEnti } - public function doFlush(): array + public function doFlush(bool $keepRollbackState = false): array { $this->mapper->flush(); $this->onFlush($this->entitiesToFlush[0], $this->entitiesToFlush[1]); $entities = $this->entitiesToFlush; $this->entitiesToFlush = [[], []]; - $this->entitiesToRollback = []; + if (!$keepRollbackState) { + $this->doFinalizeTransaction(); + } return $entities; } + public function doFinalizeTransaction(): void + { + $this->entitiesToRollback = []; + } + + public function doClear(): void { $managedIds = []; diff --git a/tests/cases/integration/Model/model.transactional.phpt b/tests/cases/integration/Model/model.transactional.phpt new file mode 100644 index 000000000..0d143ae89 --- /dev/null +++ b/tests/cases/integration/Model/model.transactional.phpt @@ -0,0 +1,195 @@ +section === Helper::SECTION_ARRAY) { + Environment::skip('Transaction callbacks require a transactional mapper.'); + } + } + + + public function testReadAndMultipleRepositoriesBelongToTransaction(): void + { + $connection = $this->container->getByType(IConnection::class); + $result = $this->orm->transactional(static function (TestAppModel $orm) use ($connection): int { + Assert::same(1, $connection->getTransactionNestedIndex()); + $author = $orm->authors->getByIdChecked(1); + $publisher = $orm->publishers->getByIdChecked(1); + $author->name = 'Transactional author'; + $publisher->name = 'Transactional publisher'; + $orm->persist($author); + $orm->persistAndFlush($publisher); + Assert::same(1, $connection->getTransactionNestedIndex()); + return 42; + }); + Assert::same(42, $result); + Assert::same(0, $connection->getTransactionNestedIndex()); + Assert::same('Transactional author', $connection->query('SELECT name FROM authors WHERE id = 1')->fetchField()); + Assert::same('Transactional publisher', $connection->query('SELECT name FROM publishers WHERE publisher_id = 1')->fetchField()); + } + + + public function testPersistenceFailureInvalidatesBothEntitiesAndAllowsReuse(): void + { + $first = new Author(); + $first->name = 'First'; + $second = new Author(); + $second->name = str_repeat('x', 1000); + Assert::exception(function () use ($first, $second): void { + $this->orm->transactional(static function (TestAppModel $orm) use ($first, $second): void { + $orm->persist($first); + $orm->persist($second); + }); + }, QueryException::class); + Assert::false($first->isAttached()); + Assert::false($first->isPersisted()); + Assert::false($second->isAttached()); + Assert::false($second->isPersisted()); + $connection = $this->container->getByType(IConnection::class); + Assert::same(0, $connection->getTransactionNestedIndex()); + Assert::same(0, $connection->query('SELECT COUNT(*) FROM authors WHERE name = %s', 'First')->fetchField()); + + $fresh = new Author(); + $fresh->name = 'Fresh'; + $this->orm->transactional(static function (TestAppModel $orm) use ($fresh): void { + $orm->persist($fresh); + }); + Assert::true($fresh->isPersisted()); + Assert::same(0, $connection->getTransactionNestedIndex()); + } + + + public function testErrorAfterFlushStillRollsBack(): void + { + $author = new Author(); + $author->name = 'Rolled back'; + Assert::exception(function () use ($author): void { + $this->orm->transactional(static function (TestAppModel $orm) use ($author): void { + $orm->persistAndFlush($author); + throw new TypeError('Application failed after flush'); + }); + }, TypeError::class); + Assert::false($author->isAttached()); + Assert::false($author->isPersisted()); + $connection = $this->container->getByType(IConnection::class); + Assert::same(0, $connection->query('SELECT COUNT(*) FROM authors WHERE name = %s', 'Rolled back')->fetchField()); + } + + + public function testCaughtPersistenceFailureStillAbortsScope(): void + { + $author = new Author(); + $author->name = str_repeat('x', 1000); + Assert::exception(function () use ($author): void { + $this->orm->transactional(static function (TestAppModel $orm) use ($author): void { + try { + $orm->persist($author); + } catch (QueryException) { + // Catching the write error does not make partially modified ORM state safe to commit. + } + }); + }, QueryException::class); + Assert::false($author->isAttached()); + Assert::same(0, $this->container->getByType(IConnection::class)->getTransactionNestedIndex()); + } + + + public function testRemovedEntityIsInvalidatedAfterFlushAndFailure(): void + { + $book = $this->orm->books->getByIdChecked(1); + Assert::exception(function () use ($book): void { + $this->orm->transactional(static function (TestAppModel $orm) use ($book): void { + $orm->removeAndFlush($book, false); + throw new TypeError('Application failed after removal'); + }); + }, TypeError::class); + Assert::false($book->isAttached()); + Assert::false($book->isPersisted()); + Assert::notSame($book, $this->orm->books->getByIdChecked(1)); + } + + + public function testBeforePersistFailureInvalidatesAttemptedEntity(): void + { + $author = new Author(); + $author->name = 'Never written'; + $this->orm->authors->onBeforePersist[] = static fn() => throw new TypeError('Before persist failed'); + Assert::exception(function () use ($author): void { + $this->orm->transactional(static function (TestAppModel $orm) use ($author): void { + $orm->persist($author); + }); + }, TypeError::class); + Assert::false($author->isAttached()); + Assert::false($author->hasValue('name')); + } + + + public function testNestedScopeIsRejectedAndOuterScopeRollsBack(): void + { + Assert::exception(function (): void { + $this->orm->transactional(static function (TestAppModel $orm): void { + $orm->transactional(static fn() => null); + }); + }, InvalidStateException::class, 'Nested Model::transactional() calls are not supported.'); + $connection = $this->container->getByType(IConnection::class); + Assert::same(0, $connection->getTransactionNestedIndex()); + } + + + public function testExistingConnectionTransactionIsPreservedOnRejection(): void + { + $connection = $this->container->getByType(IConnection::class); + $connection->beginTransaction(); + try { + Assert::exception(fn() => $this->orm->transactional(static fn() => null), InvalidStateException::class); + Assert::same(1, $connection->getTransactionNestedIndex()); + } finally { + $connection->rollbackTransaction(); + } + } + + + public function testExistingUnflushedWritesArePreservedOnRejection(): void + { + $author = new Author(); + $author->name = 'Before transaction'; + $this->orm->persist($author); + Assert::exception(fn() => $this->orm->transactional(static fn() => null), InvalidStateException::class); + Assert::true($author->isPersisted()); + Assert::true($author->isAttached()); + $this->orm->flush(); + $connection = $this->container->getByType(IConnection::class); + Assert::same(1, $connection->query('SELECT COUNT(*) FROM authors WHERE name = %s', 'Before transaction')->fetchField()); + } +} + + +(new ModelTransactionalTest())->run(); diff --git a/tests/cases/unit/Mapper/Dbal/DbalMapperCoordinatorTest.phpt b/tests/cases/unit/Mapper/Dbal/DbalMapperCoordinatorTest.phpt index c48b030e3..71cd8572e 100644 --- a/tests/cases/unit/Mapper/Dbal/DbalMapperCoordinatorTest.phpt +++ b/tests/cases/unit/Mapper/Dbal/DbalMapperCoordinatorTest.phpt @@ -26,12 +26,11 @@ class DbalMapperCoordinatorTest extends TestCase $connection->shouldReceive('beginTransaction')->once(); $connection->shouldReceive('rollbackTransaction')->once(); $coordinator = new DbalMapperCoordinator($connection); - Assert::noError(static function () use ($coordinator): void { - $coordinator->beginTransaction(); - $coordinator->beginTransaction(); - $coordinator->rollback(); - $coordinator->rollback(); - }); + $coordinator->beginTransaction(); + $coordinator->beginTransaction(); + $coordinator->rollback(); + $coordinator->rollback(); + Assert::same($connection, $coordinator->getConnection()); } @@ -47,6 +46,30 @@ class DbalMapperCoordinatorTest extends TestCase } + public function testManagedFlushDoesNotCommitAndFailedCommitAllowsReuse(): void + { + $failure = new RuntimeException('Commit failed'); + $connection = Mockery::mock(IConnection::class); + $connection->shouldReceive('connect')->once(); + $connection->shouldReceive('getTransactionNestedIndex')->once()->andReturn(0); + $connection->shouldReceive('transactional')->once()->andReturnUsing(static function (callable $callback) use ($failure): void { + $callback(); + throw $failure; + }); + $connection->shouldReceive('beginTransaction')->once(); + $connection->shouldReceive('commitTransaction')->once(); + $coordinator = new DbalMapperCoordinator($connection); + Assert::same($failure, Assert::exception(function () use ($coordinator): void { + $coordinator->transactional(static function () use ($coordinator): void { + $coordinator->beginTransaction(); + $coordinator->flush(); + }); + }, RuntimeException::class)); + $coordinator->beginTransaction(); + $coordinator->flush(); + } + + protected function tearDown(): void { Mockery::close(); diff --git a/tests/cases/unit/Model/Model.transactions.phpt b/tests/cases/unit/Model/Model.transactions.phpt new file mode 100644 index 000000000..7d1add93a --- /dev/null +++ b/tests/cases/unit/Model/Model.transactions.phpt @@ -0,0 +1,115 @@ +shouldReceive('getTransactionCoordinator')->once()->andReturn(Mockery::mock(ITransactionCoordinator::class)); + $second = Mockery::mock(IMapper::class, ITransactionalMapper::class); + $second->shouldReceive('getTransactionCoordinator')->once()->andReturn(Mockery::mock(ITransactionCoordinator::class)); + $firstRepository = Mockery::mock(IRepository::class); + $firstRepository->shouldReceive('getMapper')->once()->andReturn($first); + $secondRepository = Mockery::mock(IRepository::class); + $secondRepository->shouldReceive('getMapper')->once()->andReturn($second); + $loader = Mockery::mock(IRepositoryLoader::class); + $loader->shouldReceive('getRepositories')->once()->andReturn([$firstRepository, $secondRepository]); + $model = new Model($loader, Mockery::mock(MetadataStorage::class)); + Assert::exception( + fn() => $model->transactional(static fn() => Assert::fail('Callback must not run')), + NotSupportedException::class, + ); + } + + + public function testUnsupportedMapperIsRejectedBeforeCallback(): void + { + $repository = Mockery::mock(IRepository::class); + $repository->shouldReceive('getMapper')->once()->andReturn(Mockery::mock(IMapper::class)); + $loader = Mockery::mock(IRepositoryLoader::class); + $loader->shouldReceive('getRepositories')->once()->andReturn([$repository]); + $model = new Model($loader, Mockery::mock(MetadataStorage::class)); + Assert::exception( + fn() => $model->transactional(static fn() => Assert::fail('Callback must not run')), + NotSupportedException::class, + ); + } + + + public function testCommitFailureResetsStateAndPreservesOriginalException(): void + { + $failure = new RuntimeException('Commit failed'); + $coordinator = Mockery::mock(ITransactionCoordinator::class); + $coordinator->shouldReceive('transactional')->once()->andReturnUsing(static function (callable $callback) use ($failure): void { + $callback(); + throw $failure; + }); + $mapper = Mockery::mock(IMapper::class, ITransactionalMapper::class); + $mapper->shouldReceive('getTransactionCoordinator')->once()->andReturn($coordinator); + $repository = Mockery::mock(IRepository::class); + $repository->shouldReceive('getMapper')->once()->andReturn($mapper); + $repository->shouldReceive('doFlush')->once()->andReturn([[], []]); + $repository->shouldReceive('doClear')->once(); + $loader = Mockery::mock(IRepositoryLoader::class); + $loader->shouldReceive('getRepositories')->once()->andReturn([$repository]); + $loader->shouldReceive('getInitializedRepositories')->twice()->andReturn([$repository]); + $model = new Model($loader, Mockery::mock(MetadataStorage::class)); + Assert::same($failure, Assert::exception(fn() => $model->transactional(static fn() => 42), RuntimeException::class)); + } + + + public function testFailedStateResetPreservesCallbackException(): void + { + $failure = new TypeError('Callback failed'); + $resetFailure = new RuntimeException('Cleanup failed'); + $coordinator = Mockery::mock(ITransactionCoordinator::class); + $coordinator->shouldReceive('transactional')->once()->andReturnUsing(static fn(callable $callback) => $callback()); + $mapper = Mockery::mock(IMapper::class, ITransactionalMapper::class); + $mapper->shouldReceive('getTransactionCoordinator')->once()->andReturn($coordinator); + $repository = Mockery::mock(IRepository::class); + $repository->shouldReceive('getMapper')->once()->andReturn($mapper); + $repository->shouldReceive('doClear')->once()->andThrow($resetFailure); + $loader = Mockery::mock(IRepositoryLoader::class); + $loader->shouldReceive('getRepositories')->once()->andReturn([$repository]); + $loader->shouldReceive('getInitializedRepositories')->once()->andReturn([$repository]); + $model = new Model($loader, Mockery::mock(MetadataStorage::class)); + $exception = Assert::exception(fn() => $model->transactional(static fn() => throw $failure), RollbackException::class); + Assert::type(RollbackException::class, $exception); + Assert::same($failure, $exception->getPrevious()); + Assert::same([$resetFailure], $exception->getCleanupErrors()); + } + + + protected function tearDown(): void + { + Mockery::close(); + } +} + + +(new ModelTransactionsTest())->run();