Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down
6 changes: 6 additions & 0 deletions docs/migrate_6.0.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

### BC Breaks

- **`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`.

- **`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()`).
Expand Down Expand Up @@ -48,6 +52,8 @@

### New Features

- **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).

- **`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:
Expand Down
38 changes: 38 additions & 0 deletions docs/model.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,44 @@ $model->flush();
```


#### Transactions and rollback

`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 {
$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, 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

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.
Expand Down
25 changes: 13 additions & 12 deletions docs/unique-constraint.md
Original file line number Diff line number Diff line change
@@ -1,21 +1,22 @@
## 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.
A concurrent request can insert a row before your request does. Dbal converts a duplicate-key error into `UniqueConstraintViolationException`, which the application can catch.

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.
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->likes->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->likes->getMapper()->rollback();
$this->orm->refreshAll()
// Obtain fresh entities here, for example to find the already existing like.
}
```

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).
12 changes: 12 additions & 0 deletions src/Bridges/NetteDI/DiRepositoryLoader.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
31 changes: 31 additions & 0 deletions src/Exception/RollbackException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php declare(strict_types = 1);

namespace Nextras\Orm\Exception;


use Throwable;


/**
* Rollback or state cleanup failed. Discard the model and its entities after this exception.
*/
class RollbackException extends RuntimeException
{
public function __construct(
/** @var non-empty-list<Throwable> */
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<Throwable>
*/
public function getCleanupErrors(): array
{
return $this->cleanupErrors;
}
}
14 changes: 13 additions & 1 deletion src/Mapper/Dbal/DbalMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@
use Nextras\Orm\Mapper\Dbal\Conventions\Inflector\SnakeCaseInflector;
use Nextras\Orm\Mapper\IMapper;
use Nextras\Orm\Mapper\IRelationshipMapper;
use Nextras\Orm\Mapper\ITransactionalMapper;
use Nextras\Orm\Mapper\ITransactionCoordinator;
use Nextras\Orm\Repository\IRepository;
use Nextras\Orm\StorageReflection\StringHelper;

Expand All @@ -34,7 +36,7 @@
* @template E of IEntity
* @implements IMapper<E>
*/
abstract class DbalMapper implements IMapper
abstract class DbalMapper implements IMapper, ITransactionalMapper
{
/**
* Database table name.
Expand Down Expand Up @@ -62,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);
}
Expand Down Expand Up @@ -531,6 +536,13 @@ public function flush(): void
}


#[\NoDiscard]
public function getTransactionCoordinator(): ITransactionCoordinator
{
return $this->mapperCoordinator;
}


public function beginTransaction(): void
{
$this->mapperCoordinator->beginTransaction();
Expand Down
69 changes: 66 additions & 3 deletions src/Mapper/Dbal/DbalMapperCoordinator.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,21 @@
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;


public function __construct(
private readonly IConnection $connection,
Expand All @@ -18,8 +26,16 @@ public function __construct(
}


#[\NoDiscard]
public function getConnection(): IConnection
{
return $this->connection;
}


public function beginTransaction(): void
{
$this->checkUsable();
if (!$this->transactionActive) {
$this->connection->beginTransaction();
$this->transactionActive = true;
Expand All @@ -29,7 +45,8 @@ public function beginTransaction(): void

public function flush(): void
{
if ($this->transactionActive) {
$this->checkUsable();
if ($this->transactionActive && !$this->managedTransaction) {
$this->connection->commitTransaction();
$this->transactionActive = false;
}
Expand All @@ -38,9 +55,55 @@ 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) {
$this->connection->rollbackTransaction();
try {
$this->connection->rollbackTransaction();
} catch (Throwable $e) {
$this->rollbackFailure = $e;
throw $e;
} finally {
$this->transactionActive = false;
}
}
}


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) {
throw new InvalidStateException(
'The transaction coordinator cannot be reused after rollback failed.',
0,
$this->rollbackFailure,
);
}
}
}
12 changes: 12 additions & 0 deletions src/Mapper/IRollbackableMapper.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?php declare(strict_types = 1);

namespace Nextras\Orm\Mapper;


/**
* Optional capability for mappers whose unflushed writes can be rolled back.
*/
interface IRollbackableMapper
{
public function rollback(): void;
}
16 changes: 16 additions & 0 deletions src/Mapper/ITransactionCoordinator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php declare(strict_types = 1);

namespace Nextras\Orm\Mapper;


interface ITransactionCoordinator
{
/**
* Runs an outermost transaction. Mapper flushes inside the callback must not commit it.
* Rejects entry if the resource already has an active transaction.
* @template T
* @param callable(): T $callback
* @return T
*/
public function transactional(callable $callback): mixed;
}
13 changes: 13 additions & 0 deletions src/Mapper/ITransactionalMapper.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php declare(strict_types = 1);

namespace Nextras\Orm\Mapper;


/**
* Mappers sharing one storage transaction must return the same coordinator instance.
*/
interface ITransactionalMapper extends IRollbackableMapper
{
#[\NoDiscard]
public function getTransactionCoordinator(): ITransactionCoordinator;
}
4 changes: 3 additions & 1 deletion src/Mapper/Memory/ArrayMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
use Nextras\Orm\Exception\IOException;
use Nextras\Orm\Exception\LogicException;
use Nextras\Orm\Mapper\IMapper;
use Nextras\Orm\Mapper\IRollbackableMapper;
use Nextras\Orm\Mapper\Memory\Conventions\Conventions;
use Nextras\Orm\Mapper\Memory\Conventions\IConventions;
use Nextras\Orm\Repository\IRepository;
Expand All @@ -24,7 +25,7 @@
* @template E of IEntity
* @implements IMapper<E>
*/
abstract class ArrayMapper implements IMapper
abstract class ArrayMapper implements IMapper, IRollbackableMapper
{
/** @var array<int|string, mixed>|null */
protected array|null $data = null;
Expand Down Expand Up @@ -198,6 +199,7 @@ public function flush(): void
public function rollback(): void
{
$this->data = null;
$this->relationshipData = [];
}


Expand Down
Loading
Loading