You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Unit of work 3: Transactional database: auto-commit or rollback per endpoint (#729)
Open a transaction per request, to ensure that everything will be either
committed or rollback.
## Migration strategy
Existing `db.commit()` were replaced by `db.flush()` even when it may
not have been necessary to prevent creating unexpected regressions.
## Advanced usage
The database transaction is automatically commited at the end.
- If an HTTPException is raised during the request, we consider that the
error was expected and managed by the endpoint. We commit the session.
- If an other exception is raised, we rollback the session to avoid.
> Cruds and endpoints should never call `db.commit()` or `db.rollback()`
directly.
>After adding an object to the session, calling `await db.flush()` will
integrate the changes in the transaction without committing them.
> If an endpoint needs to add objects to the sessions that should be
committed even in case of an unexpected error, it should start a
SAVEPOINT after adding the object.
> ```python
> # Add here the object that should always be committed, even in case of
an unexpected error
> await db.add(object)
> await db.flush()
> # Start a SAVEPOINT. If the code in the following context manager
raises an exception, the changes will be rolled back to this point.
> async with db.begin_nested():
> # Add objects that may be rolled back in case of an error here
> ```
---
Supersede #498
0 commit comments