New strategy for transaction management.

Introduce a contextmanger function to handle exceptions and nested
transactions. Using the nested_transaction will start a
nested transaction with `db.session.begin_nested`, once the nested
transaction is complete the commit will happen.
`@transactional` has been updated to commit unless in a nested
transaction.
This commit is contained in:
Rebecca Law
2021-04-13 15:02:46 +01:00
parent cf35135605
commit 93908bacda
9 changed files with 29 additions and 52 deletions

View File

@@ -1,4 +1,5 @@
import itertools
from contextlib import contextmanager
from functools import wraps
from app import db
@@ -10,7 +11,10 @@ def transactional(func):
def commit_or_rollback(*args, **kwargs):
try:
res = func(*args, **kwargs)
db.session.commit()
if not db.session.registry().transaction.nested:
db.session.commit()
return res
except Exception:
db.session.rollback()
@@ -18,21 +22,18 @@ def transactional(func):
return commit_or_rollback
def nested_transactional(func):
# This creates a save point for the nested transaction.
# You must manage the commit or rollback from outer most call of the nested of the transactions.
@wraps(func)
def commit_or_rollback(*args, **kwargs):
try:
db.session.begin_nested()
res = func(*args, **kwargs)
db.session.commit()
return res
except Exception:
db.session.rollback()
raise
@contextmanager
def nested_transaction():
try:
db.session.begin_nested()
yield
db.session.commit()
return commit_or_rollback
if not db.session.registry().transaction.nested:
db.session.commit()
except Exception:
db.session.rollback()
raise
class VersionOptions():