Skip to content

Commit

Permalink
uow: add "on_exception" lifecycle hook
Browse files Browse the repository at this point in the history
- When an exception occurs and the unit of work is being rolled back, we
  want to add the possibility to perform some clean-up actions that can
  also be commited to the database.
- The new `on_exception` method is added because we want to keep
  backwards compatibility and also introduce the same "triplet" of
  methods as we have for the "happy path" (`on_register`, `on_commit`,
  `on_post_commit`).
  • Loading branch information
slint committed Oct 30, 2024
1 parent 305b5b1 commit c84b1dd
Showing 1 changed file with 15 additions and 3 deletions.
18 changes: 15 additions & 3 deletions invenio_db/uow.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,10 @@ def on_post_commit(self, uow):
"""Called right after the commit phase."""
pass

def on_exception(self, uow, exception):
"""Called in case of an exception."""
pass

def on_rollback(self, uow):
"""Called in the rollback phase (after the transaction rollback)."""
pass
Expand Down Expand Up @@ -165,10 +169,10 @@ def __enter__(self):
"""Entering the context."""
return self

def __exit__(self, exc_type, *args):
def __exit__(self, exc_type, exc_value, traceback):
"""Rollback on exception."""
if exc_type is not None:
self.rollback()
self.rollback(exception=exc_value)
self._mark_dirty()

@property
Expand All @@ -193,9 +197,17 @@ def commit(self):
op.on_post_commit(self)
self._mark_dirty()

def rollback(self):
def rollback(self, exception=None):
"""Rollback the database session."""
self.session.rollback()

# Run exception operations
for op in self._operations:
op.on_exception(self, exception)

# Commit exception operations
self.session.commit()

# Run rollback operations
for op in self._operations:
op.on_rollback(self)
Expand Down

0 comments on commit c84b1dd

Please sign in to comment.