[IMP] add cursor() contextmanager on registry
authorChristophe Simonis <chs@openerp.com>
Mon, 13 Aug 2012 15:05:01 +0000 (17:05 +0200)
committerChristophe Simonis <chs@openerp.com>
Mon, 13 Aug 2012 15:05:01 +0000 (17:05 +0200)
bzr revid: chs@openerp.com-20120813150501-txkrphi7hyp2tgl1

openerp/modules/registry.py

index 7c7a5c9..ae9772b 100644 (file)
@@ -22,6 +22,7 @@
 """ Models registries.
 
 """
+from contextlib import contextmanager
 import logging
 import threading
 
@@ -43,12 +44,12 @@ class Registry(object):
     """
 
     def __init__(self, db_name):
-        self.models = {} # model name/model instance mapping
+        self.models = {}    # model name/model instance mapping
         self._sql_error = {}
         self._store_function = {}
         self._init = True
         self._init_parent = {}
-        
+
         # modules fully loaded (maintained during init phase by `loading` module)
         self._init_modules = set()
 
@@ -119,6 +120,17 @@ class Registry(object):
         for model in self.models.itervalues():
             model.clear_caches()
 
+    @contextmanager
+    def cursor(self, auto_commit=True):
+        cr = self.db.cursor()
+        try:
+            yield cr
+            if auto_commit:
+                cr.commit()
+        finally:
+            cr.close()
+
+
 class RegistryManager(object):
     """ Model registries manager.
 
@@ -196,7 +208,6 @@ class RegistryManager(object):
                 del cls.registries[db_name]
                 openerp.cron.cancel(db_name)
 
-
     @classmethod
     def delete_all(cls):
         """Delete all the registries. """