[Mpuls-commits] r5384 - base/trunk/mpulsweb/lib

scm-commit@wald.intevation.org scm-commit at wald.intevation.org
Wed Sep 21 20:34:06 CEST 2011


Author: bh
Date: 2011-09-21 20:34:05 +0200 (Wed, 21 Sep 2011)
New Revision: 5384

Modified:
   base/trunk/mpulsweb/lib/db.py
Log:
Implement a context manager for DB transactions.
This is done with the new DB.transaction() method. See its doc-string
for how to use it.


Modified: base/trunk/mpulsweb/lib/db.py
===================================================================
--- base/trunk/mpulsweb/lib/db.py	2011-09-21 13:55:23 UTC (rev 5383)
+++ base/trunk/mpulsweb/lib/db.py	2011-09-21 18:34:05 UTC (rev 5384)
@@ -29,6 +29,7 @@
 #
 
 import logging
+from contextlib import contextmanager
 
 import psycopg2 as dbapi
 import psycopg2.extensions
@@ -118,6 +119,33 @@
             except:
                 log.exception("Error ignored while closing connection")
 
+    @contextmanager
+    def transaction(self):
+        """Return a context manager for performing a block within a transaction.
+        Example usage:
+            with db.transation() as cur:
+                cur.execute("UPDATE foo ...")
+                ...
+
+        The object bound to cur in the example is a database cursor that
+        can be used to execute database queries in the usual way. The
+        context manager will commit the changes once control flow leaves
+        the block if no exception is raised. If an exception is raised,
+        the transaction will be rolled back automatically.
+        """
+        has_committed = False
+        cur = None
+        con = self.getConnection()
+        try:
+            cur = con.cursor()
+            yield cur
+            con.commit()
+            has_committed = True
+        finally:
+            if not has_committed:
+                con.rollback()
+            self.recycleConnection(con, cur)
+
     def execute(self, statement, *args):
         """Execute an SQL statement in a transaction.
 



More information about the Mpuls-commits mailing list