def _update_registry(self, cr, uid, context=None): """ Update the registry after a modification on action rules. """ if self.pool.ready: # for the sake of simplicity, simply force the registry to reload cr.commit() openerp.api.Environment.reset() RegistryManager.new(cr.dbname) RegistryManager.signal_registry_change(cr.dbname)
def _update_registry(self, cr, uid, context=None): """ Update the registry after a modification on action rules. """ if self.pool.ready: # for the sake of simplicity, simply force the registry to reload cr.commit() openerp.api.Environment.reset() RegistryManager.new(cr.dbname) RegistryManager.signal_registry_change(cr.dbname)
def test_02_uninstall(self): """ Check a few things showing the module is uninstalled. """ with environment() as env: module = env['ir.module.module'].search([('name', '=', MODULE)]) assert len(module) == 1 module.button_uninstall() RegistryManager.new(common.get_db_name(), update_module=True) with environment() as env: self.assertNotIn('test_uninstall.model', env.registry) self.assertFalse(env['ir.model.data'].search([('module', '=', MODULE)])) self.assertFalse(env['ir.model.fields'].search([('model', '=', MODEL)]))
def test_02_uninstall(self): """ Check a few things showing the module is uninstalled. """ with environment() as env: module = env['ir.module.module'].search([('name', '=', MODULE)]) assert len(module) == 1 module.button_uninstall() RegistryManager.new(common.get_db_name(), update_module=True) with environment() as env: self.assertNotIn('test_uninstall.model', env.registry) self.assertFalse(env['ir.model.data'].search([('module', '=', MODULE)])) self.assertFalse(env['ir.model.fields'].search([('model', '=', MODEL)]))
def __enter__(self): """ Context enter function. Temporarily add odoo 8 server path to system path and pop afterwards. Import odoo 8 server from path as library. Init logger, registry and environment. Add addons path to config. :returns Odoo8Context: This instance """ sys.path.append(self.server_path) from openerp import netsvc, api from openerp.modules.registry import RegistryManager from openerp.tools import trans_export, config, trans_load_data self.trans_export = trans_export self.trans_load_data = trans_load_data sys.path.pop() netsvc.init_logger() config['addons_path'] = ( config.get('addons_path') + ',' + self.addons_path ) registry = RegistryManager.new(self.dbname) self.environment_manage = api.Environment.manage() self.environment_manage.__enter__() self.cr = registry.cursor() return self
def preload_registries(dbnames): """ Preload a registries, possibly run a test file.""" # TODO: move all config checks to args dont check tools.config here config = openerp.tools.config test_file = config['test_file'] dbnames = dbnames or [] rc = 0 for dbname in dbnames: try: update_module = config['init'] or config['update'] registry = RegistryManager.new(dbname, update_module=update_module) # run test_file if provided if test_file: _logger.info('loading test file %s', test_file) with openerp.api.Environment.manage(): if test_file.endswith('yml'): load_test_file_yml(registry, test_file) elif test_file.endswith('py'): load_test_file_py(registry, test_file) if registry._assertion_report.failures: rc += 1 except Exception: _logger.critical('Failed to initialize database `%s`.', dbname, exc_info=True) return -1 return rc
def odoo_preload_registry(dbnames): """ Preload a registry, and start the cron.""" config = openerp.tools.config for db_name in dbnames: try: _log.info("preload registery[%s] dbname=%s" % (os.getpid(), db_name)) update_module = config['init'] or config['update'] modules = {} if config['init']: m = config['init'].split(",") for i in m: modules[i] = True config['init'] = modules elif config['update']: m = config['update'].split(",") for i in m: modules[i] = True config['update'] = modules registry = RegistryManager.new(db_name, update_module=update_module) except Exception, ex: _log.exception('Failed to initialize database `%s`.', db_name) _log.exception(ex)
def __enter__(self): """ Context enter function. Temporarily add odoo 8 server path to system path and pop afterwards. Import odoo 8 server from path as library. Init logger, registry and environment. Add addons path to config. :returns Odoo8Context: This instance """ sys.path.append(self.server_path) from openerp import netsvc, api from openerp.modules.registry import RegistryManager from openerp.tools import trans_export, config, trans_load_data self.trans_export = trans_export self.trans_load_data = trans_load_data sys.path.pop() netsvc.init_logger() config['addons_path'] = ( config.get('addons_path') + ',' + self.addons_path ) registry = RegistryManager.new(self.dbname) self.environment_manage = api.Environment.manage() self.environment_manage.__enter__() self.cr = registry.cursor() return self
def preload(ctx, modules): config = (ctx.obj['config']) from openerp.modules.registry import RegistryManager registry = RegistryManager.new(config['db_name'], False, None, update_module=True)
def purge(self): """ Uninstall modules upon manual confirmation, then reload the database. """ module_names = self.filtered(lambda x: not x.purged).mapped('name') modules = self.env['ir.module.module'].search([('name', 'in', module_names)]) if not modules: return True self.logger.info('Purging modules %s', ', '.join(module_names)) modules.button_uninstall() # we need this commit because reloading the registry would roll back # our changes self.env.cr.commit() # pylint: disable=invalid-commit RegistryManager.new(self.env.cr.dbname, update_module=True) modules.unlink() return self.write({'purged': True})
def purge(self): """ Uninstall modules upon manual confirmation, then reload the database. """ module_names = self.filtered(lambda x: not x.purged).mapped('name') modules = self.env['ir.module.module'].search([ ('name', 'in', module_names) ]) if not modules: return True self.logger.info('Purging modules %s', ', '.join(module_names)) modules.write({'state': 'to remove'}) # we need this commit because reloading the registry would roll back # our changes self.env.cr.commit() # pylint: disable=invalid-commit RegistryManager.new(self.env.cr.dbname, update_module=True) modules.unlink() return self.write({'purged': True})
def unlink(self, cr, user, ids, context=None): # Prevent manual deletion of module columns if context is None: context = {} if isinstance(ids, (int, long)): ids = [ids] if not context.get(MODULE_UNINSTALL_FLAG) and \ any(field.state != 'manual' for field in self.browse(cr, user, ids, context)): raise UserError( _("This column contains module data and cannot be removed!")) self._drop_column(cr, user, ids, context) res = super(HrPerformanceFields, self).unlink(cr, user, ids, context) if not context.get(MODULE_UNINSTALL_FLAG): # The field we just deleted might be inherited, and the registry is # inconsistent in this case; therefore we reload the registry. cr.commit() api.Environment.reset() RegistryManager.new(cr.dbname) RegistryManager.signal_registry_change(cr.dbname) return res
def button_reload(self, cr, uid, ids, context=None): for module_record in self.browse(cr, uid, ids, context=context): #Remove any report parsers registered for this module. module_path = 'addons/' + module_record.name for service_name, service in Service._services.items(): template = getattr(service, 'tmpl', '') if type(template) == type(''): if template.startswith(module_path): Service.remove(service_name) #Remove any model classes registered for this module MetaModel.module_to_models[module_record.name] = [] #Reload all Python modules from the OpenERP module's directory. modulename = 'openerp.addons.' + module_record.name root = __import__(modulename) module = getattr(root.addons, module_record.name) reimport(module) RegistryManager.delete(cr.dbname) RegistryManager.new(cr.dbname) return {}
def __enter__(self): """ Context enter function. Temporarily add odoo 8 server path to system path and pop afterwards. Import odoo 8 server from path as library. Init logger, registry and environment. Add addons path to config. :returns Odoo8Context: This instance """ netsvc.init_logger() registry = RegistryManager.new(self.dbname) self._environment_manage = api.Environment.manage() self._environment_manage.__enter__() self._cr = registry.cursor() self._uid = SUPERUSER_ID self._context = registry("res.users").context_get(self._cr, self._uid) self.env = api.Environment(self._cr, self._uid, self._context) return self
def restart_pool(db_name, force_demo=False, status=None, update_module=False): """Delete an existing registry and return a database connection and a newly initialized registry.""" registry = RegistryManager.new(db_name, force_demo, status, update_module) return registry.db, registry
def restart_pool(db_name, force_demo=False, status=None, update_module=False): """Delete an existing registry and return a database connection and a newly initialized registry.""" registry = RegistryManager.new(db_name, force_demo, status, update_module, True) return registry.db, registry
def restart_pool(db_name, force_demo=False, status=None, update_module=False): """Delete an existing registry and return a database connection and a newly initialized registry.""" _logger.warning('openerp.pooler.restart_pool() is deprecated.') assert openerp.conf.deprecation.openerp_pooler registry = RegistryManager.new(db_name, force_demo, status, update_module) return registry._db, registry
def action_create(self): def _get_fields_info(fields_data): fields_info = [] for field_data in fields_data: field = self.env['ir.model.fields'].browse(field_data["id"]) vals = { "table": self.env[field.model_id.model]._table, "table_alias": field_data["table_alias"], "select_field": field.name, "as_field": "x_" + field_data["name"], "join": False, "model": field.model_id.model } if field_data.get("join_node"): vals.update({"join": field_data["join_node"]}) fields_info.append(vals) return fields_info def _build_query(): info = _get_fields_info(json.loads(self.data)) fields = [("{}.{}".format(f["table_alias"], f["select_field"]), f["as_field"]) for f in info if 'join_node' not in f] tables = set([(f["table"], f["table_alias"]) for f in info]) join_nodes = [(f["table_alias"], f["join"], f["select_field"]) for f in info if f["join"] is not False] table_name = self.model_name.replace(".", "_") tools.drop_view_if_exists(self.env.cr, table_name) basic_fields = [("t0.id", "id"), ("t0.write_uid", "write_uid"), ("t0.write_date", "write_date"), ("t0.create_uid", "create_uid"), ("t0.create_date", "create_date")] q = """CREATE or REPLACE VIEW %s as ( SELECT %s FROM %s WHERE %s )""" % (table_name, ','.join([ "{} AS {}".format(f[0], f[1]) for f in basic_fields + fields ]), ','.join([ "{} AS {}".format(t[0], t[1]) for t in list(tables) ]), " AND ".join( ["{}.{} = {}.id".format(j[0], j[2], j[1]) for j in join_nodes] + ["TRUE"])) self.env.cr.execute(q) def _prepare_field(field_data): if not field_data["custom"]: field = self.env['ir.model.fields'].browse(field_data["id"]) vals = { "name": "x_" + field_data["name"], "complete_name": field.complete_name, 'model': self.model_name, 'relation': field.relation, "field_description": field_data.get("description", field.field_description), "ttype": field.ttype, "selection": field.selection, "size": field.size, 'state': "manual" } if field.ttype == 'selection' and not field.selection: model_obj = self.env[field.model_id.model] selection = model_obj._columns[field.name].selection selection_domain = str(selection) vals.update({"selection": selection_domain}) return vals def _prepare_object(): return { 'name': self.name, 'model': self.model_name, 'field_id': [(0, 0, _prepare_field(field)) for field in json.loads(self.data) if 'join_node' not in field] } def _build_object(): res_id = self.env['ir.model'].sudo().create(_prepare_object()) return res_id # read access def group_ids_with_access(model_name, access_mode): self.env.cr.execute( '''SELECT g.id FROM ir_model_access a JOIN ir_model m ON (a.model_id=m.id) JOIN res_groups g ON (a.group_id=g.id) LEFT JOIN ir_module_category c ON (c.id=g.category_id) WHERE m.model=%s AND a.active IS True AND a.perm_''' + access_mode, (model_name, )) return [x[0] for x in self.env.cr.fetchall()] def _build_access_rules(obj): info = json.loads(self.data) models = list(set([f["model"] for f in info])) read_groups = set.intersection(*[ set(group_ids_with_access(model, 'read')) for model in models ]) for group in read_groups: self.env['ir.model.access'].sudo().create({ 'name': 'read access to ' + self.model_name, 'model_id': obj.id, 'group_id': group, 'perm_read': True, }) # edit access for group in self.group_ids: self.env['ir.model.access'].sudo().create({ 'name': 'read access to ' + self.model_name, 'model_id': obj.id, 'group_id': group.id, 'perm_read': True, 'perm_write': True, }) return self.model_name = "x_bve." + ''.join([ x for x in self.name.lower() if x.isalnum() ]).replace("_", ".").replace(" ", ".") _build_query() obj = _build_object() _build_access_rules(obj) self.env.cr.commit() from openerp.modules.registry import RegistryManager self.env.registry = RegistryManager.new(self.env.cr.dbname) RegistryManager.signal_registry_change(self.env.cr.dbname) self.pool = self.env.registry view_id = self.pool.get('ir.ui.view').create( self.env.cr, SUPERUSER_ID, { 'name': "Analysis", 'type': 'graph', 'model': self.model_name, 'priority': 16, 'arch': """<?xml version="1.0"?> <graph string="Analysis" type="pivot" stacked="True"> {} </graph> """.format("".join(self._create_graph_view())) }, context={}) view_ids = [view_id] action_vals = { 'name': self.name, 'res_model': self.model_name, 'type': 'ir.actions.act_window', 'view_type': 'form', 'view_mode': 'graph', 'view_id': view_ids and view_ids[0] or 0, 'context': "{'service_name': '%s'}" % self.name, } act_window = self.env['ir.actions.act_window'] action_id = act_window.sudo().create(action_vals) self.write({ 'action_id': action_id.id, 'view_id': view_id, 'state': 'created' }) return True