Add context management methode to dbapi.Connection stable
authorPierre-Yves David <pierre-yves.david@logilab.fr>
Wed, 31 Mar 2010 11:52:15 +0200
branchstable
changeset 5100 04c71ebf38a5
parent 5099 da66ad091745
child 5101 0d01acee1f0a
Add context management methode to dbapi.Connection the connection is automaticly closed when exiting the context.
dbapi.py
--- a/dbapi.py	Wed Mar 31 11:41:20 2010 +0200
+++ b/dbapi.py	Wed Mar 31 11:52:15 2010 +0200
@@ -367,6 +367,16 @@
             return '<Connection %s (anonymous)>' % self.sessionid
         return '<Connection %s>' % self.sessionid
 
+    def __enter__(self):
+        return self.cursor()
+
+    def __exit__(self, exc_type, exc_val, exc_tb):
+        if exc_type is None:
+            self.commit()
+        else:
+            self.rollback()
+            return False #propagate the exception
+
     def request(self):
         return DBAPIRequest(self.vreg, self)