"""Database utilities.""" from functools import wraps from product_review.api import db class DBTransaction: """Database transaction decorator and context manager. Instances of this class can be used as a decorator or context manager that wraps functionality in a database transaction. """ def __call__(self, func): """Call. This gets called when the instance is used as a decorator. """ @wraps(func) def wrapper(*args, **kwargs): with self: return func(*args, **kwargs) return wrapper def __enter__(self): """Enter. This gets called when the instance is used as a context manager. """ with db.session.begin(): yield self def __exit__(self, exc_type, exc_value, _): """Exit. This gets called when the instance is used as a context manager. """ if exc_type is None: db.session.commit() else: db.session.rollback() raise exc_value db_transaction = DBTransaction()