mirror of
https://github.com/GSA/notifications-api.git
synced 2026-09-05 23:58:25 -04:00
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:
@@ -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():
|
||||
|
||||
Reference in New Issue
Block a user