[IMP] registry: add method get_cursor() to simply retrieve a new cursor, and refactor code to use it

bzr revid: rco@openerp.com-20140408125122-ki0zmin3m21k2itd
This commit is contained in:
Raphael Collet 2014-04-08 14:51:22 +02:00
parent b49f536baf
commit 6bc60505f4
13 changed files with 29 additions and 44 deletions

View File

@ -388,7 +388,7 @@ class res_users(osv.osv):
if not password:
return False
user_id = False
cr = self.pool.db.cursor()
cr = self.pool.get_cursor()
try:
# autocommit: our single update request will be performed atomically.
# (In this way, there is no opportunity to have two transactions
@ -440,7 +440,7 @@ class res_users(osv.osv):
# Successfully logged in as admin!
# Attempt to guess the web base url...
if user_agent_env and user_agent_env.get('base_location'):
cr = self.pool.db.cursor()
cr = self.pool.get_cursor()
try:
base = user_agent_env['base_location']
ICP = self.pool['ir.config_parameter']
@ -461,7 +461,7 @@ class res_users(osv.osv):
raise openerp.exceptions.AccessDenied()
if self._uid_cache.get(db, {}).get(uid) == passwd:
return
cr = self.pool.db.cursor()
cr = self.pool.get_cursor()
try:
self.check_credentials(cr, uid, passwd)
if self._uid_cache.has_key(db):

View File

@ -21,7 +21,7 @@ def registry(model):
return openerp.modules.registry.RegistryManager.get(DB)[model]
def cursor():
return openerp.modules.registry.RegistryManager.get(DB).db.cursor()
return openerp.modules.registry.RegistryManager.get(DB).get_cursor()
def drop_sequence(code):

View File

@ -13,7 +13,7 @@ def registry(model):
return openerp.modules.registry.RegistryManager.get(DB)[model]
def cursor():
return openerp.modules.registry.RegistryManager.get(DB).db.cursor()
return openerp.modules.registry.RegistryManager.get(DB).get_cursor()
def get_module(module_name):
registry = openerp.modules.registry.RegistryManager.get(DB)

View File

@ -103,7 +103,7 @@ def export_translation():
fileformat = os.path.splitext(config["translate_out"])[-1][1:].lower()
buf = file(config["translate_out"], "w")
registry = openerp.modules.registry.RegistryManager.new(dbname)
cr = registry.db.cursor()
cr = registry.get_cursor()
openerp.tools.trans_export(config["language"],
config["translate_modules"] or ["all"], buf, fileformat, cr)
cr.close()
@ -117,7 +117,7 @@ def import_translation():
dbname = config['db_name']
registry = openerp.modules.registry.RegistryManager.new(dbname)
cr = registry.db.cursor()
cr = registry.get_cursor()
openerp.tools.trans_load( cr, config["translate_in"], config["language"],
context=context)
cr.commit()

View File

@ -238,7 +238,7 @@ class WebRequest(object):
# Test cursors
self._cr = openerp.tests.common.acquire_test_cursor(self.session_id)
if not self._cr:
self._cr = self.registry.db.cursor()
self._cr = self.registry.get_cursor()
return self._cr
def __enter__(self):

View File

@ -75,7 +75,7 @@ class Registry(Mapping):
# Useful only in a multi-process context.
self._any_cache_cleared = False
cr = self.db.cursor()
cr = self.get_cursor()
has_unaccent = openerp.modules.db.has_unaccent(cr)
if openerp.tools.config['unaccent'] and not has_unaccent:
_logger.warning("The option --unaccent was given but no unaccent() function was found in database.")
@ -187,9 +187,14 @@ class Registry(Mapping):
r, c)
return r, c
def get_cursor(self):
""" Return a new cursor for the database. """
return self.db.cursor()
@contextmanager
def cursor(self, auto_commit=True):
cr = self.db.cursor()
""" Manage a new cursor; commit, rollback and closing are automatic. """
cr = self.get_cursor()
try:
yield cr
if auto_commit:
@ -286,7 +291,7 @@ class RegistryManager(object):
# Yeah, crazy.
registry = cls.registries[db_name]
cr = registry.db.cursor()
cr = registry.get_cursor()
try:
registry.do_parent_store(cr)
cr.commit()
@ -342,7 +347,7 @@ class RegistryManager(object):
changed = False
if openerp.multi_process and db_name in cls.registries:
registry = cls.get(db_name)
cr = registry.db.cursor()
cr = registry.get_cursor()
try:
cr.execute("""
SELECT base_registry_signaling.last_value,
@ -388,7 +393,7 @@ class RegistryManager(object):
registry = cls.get(db_name)
if registry.any_cache_cleared():
_logger.info("At least one model cache has been cleared, signaling through the database.")
cr = registry.db.cursor()
cr = registry.get_cursor()
r = 1
try:
cr.execute("select nextval('base_cache_signaling')")
@ -403,7 +408,7 @@ class RegistryManager(object):
if openerp.multi_process and db_name in cls.registries:
_logger.info("Registry changed, signaling through the database")
registry = cls.get(db_name)
cr = registry.db.cursor()
cr = registry.get_cursor()
r = 1
try:
cr.execute("select nextval('base_registry_signaling')")

View File

@ -161,21 +161,10 @@ def execute_cr(cr, uid, obj, method, *args, **kw):
def execute_kw(db, uid, obj, method, args, kw=None):
return execute(db, uid, obj, method, *args, **kw or {})
@contextmanager
def closing_cr_and_commit(cr):
try:
yield cr
cr.commit()
except Exception:
cr.rollback()
raise
finally:
cr.close()
@check
def execute(db, uid, obj, method, *args, **kw):
threading.currentThread().dbname = db
with closing_cr_and_commit(openerp.registry(db).db.cursor()) as cr:
with openerp.registry(db).cursor() as cr:
if method.startswith('_'):
raise except_orm('Access Denied', 'Private methods (such as %s) cannot be called remotely.' % (method,))
res = execute_cr(cr, uid, obj, method, *args, **kw)
@ -190,7 +179,7 @@ def exec_workflow_cr(cr, uid, obj, signal, *args):
@check
def exec_workflow(db, uid, obj, signal, *args):
with closing_cr_and_commit(openerp.registry(db).db.cursor()) as cr:
with openerp.registry(db).cursor() as cr:
return exec_workflow_cr(cr, uid, obj, signal, *args)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:

View File

@ -49,7 +49,7 @@ def exp_render_report(db, uid, object, ids, datas=None, context=None):
self_reports[id] = {'uid': uid, 'result': False, 'state': False, 'exception': None}
cr = openerp.registry(db).db.cursor()
cr = openerp.registry(db).get_cursor()
try:
result, format = openerp.report.render_report(cr, uid, ids, object, datas, context)
if not result:
@ -87,7 +87,7 @@ def exp_report(db, uid, object, ids, datas=None, context=None):
self_reports[id] = {'uid': uid, 'result': False, 'state': False, 'exception': None}
def go(id, uid, ids, datas, context):
cr = openerp.registry(db).db.cursor()
cr = openerp.registry(db).get_cursor()
try:
result, format = openerp.report.render_report(cr, uid, ids, object, datas, context)
if not result:

View File

@ -89,7 +89,7 @@ class BaseCase(unittest2.TestCase):
"""
def cursor(self):
return self.registry.db.cursor()
return self.registry.get_cursor()
def ref(self, xid):
""" Returns database ID corresponding to a given identifier.
@ -138,7 +138,7 @@ class SingleTransactionCase(BaseCase):
@classmethod
def setUpClass(cls):
cls.registry = openerp.modules.registry.RegistryManager.get(DB)
cls.cr = cls.registry.db.cursor()
cls.cr = cls.registry.get_cursor()
cls.uid = openerp.SUPERUSER_ID
@classmethod

View File

@ -625,7 +625,7 @@ def email_send(email_from, email_to, subject, body, email_cc=None, email_bcc=Non
if not cr:
db_name = getattr(threading.currentThread(), 'dbname', None)
if db_name:
local_cr = cr = openerp.registry(db_name).db.cursor()
local_cr = cr = openerp.registry(db_name).get_cursor()
else:
raise Exception("No database cursor found, please pass one explicitly")

View File

@ -33,12 +33,9 @@ def run(args):
xs = []
ir_module_module = registry.get('ir.module.module')
cr = registry.db.cursor() # TODO context manager
try:
with registry.cursor() as cr:
ids = ir_module_module.search(cr, openerp.SUPERUSER_ID, [], {})
xs = ir_module_module.read(cr, openerp.SUPERUSER_ID, ids, [], {})
finally:
cr.close()
if xs:
print "Modules (database `%s`):" % (args.database,)

View File

@ -20,15 +20,12 @@ def run(args):
registry = openerp.modules.registry.RegistryManager.get(
args.database, update_module=False)
model = registry[args.model]
cr = registry.db.cursor() # TODO context manager
field_names = [args.field] if args.field else []
if args.short:
# ignore --field
field_names = ['name']
try:
with registry.cursor() as cr:
xs = model.read(cr, 1, args.id, field_names, {})
finally:
cr.close()
if xs:
print "Records (model `%s`, database `%s`):" % (args.model, args.database)

View File

@ -43,15 +43,12 @@ def run(args):
args.database, update_module=False)
ir_module_module = registry.get('ir.module.module')
cr = registry.db.cursor() # TODO context manager
try:
with registry.cursor() as cr:
ids = ir_module_module.search(cr, openerp.SUPERUSER_ID, [('name', 'in', args.module), ('state', '=', 'installed')], {})
if len(ids) == len(args.module):
ir_module_module.button_immediate_uninstall(cr, openerp.SUPERUSER_ID, ids, {})
else:
print "At least one module not found (database `%s`)." % (args.database,)
finally:
cr.close()
def add_parser(subparsers):
parser = subparsers.add_parser('uninstall',