From: Michael Tremer Date: Wed, 1 Nov 2017 12:12:51 +0000 (+0100) Subject: database: Support transactions X-Git-Url: http://git.ipfire.org/?a=commitdiff_plain;h=280ed84e2796e7b985e869da99ebca4443fa7fe9;p=ipfire.org.git database: Support transactions Signed-off-by: Michael Tremer --- diff --git a/webapp/backend/database.py b/webapp/backend/database.py index 1d18a4e3..37f4da05 100644 --- a/webapp/backend/database.py +++ b/webapp/backend/database.py @@ -181,6 +181,9 @@ class Connection(object): self.close() raise + def transaction(self): + return Transaction(self) + class Row(dict): """A dict that allows for object-like property access syntax.""" @@ -191,6 +194,22 @@ class Row(dict): raise AttributeError(name) +class Transaction(object): + def __init__(self, db): + self.db = db + + self.db.execute("START TRANSACTION") + + def __enter__(self): + return self + + def __exit__(self, exctype, excvalue, traceback): + if exctype is not None: + self.db.execute("ROLLBACK") + else: + self.db.execute("COMMIT") + + # Alias some common exceptions IntegrityError = psycopg2.IntegrityError OperationalError = psycopg2.OperationalError