diff --git a/openerp/addons/base/ir/ir_actions.py b/openerp/addons/base/ir/ir_actions.py index 236c6af7119..db3c7fcdbae 100644 --- a/openerp/addons/base/ir/ir_actions.py +++ b/openerp/addons/base/ir/ir_actions.py @@ -510,7 +510,7 @@ class actions_server(osv.osv): 'code':fields.text('Python Code', help="Python code to be executed if condition is met.\n" "It is a Python block that can use the same values as for the condition field"), 'sequence': fields.integer('Sequence', help="Important when you deal with multiple actions, the execution order will be decided based on this, low number is higher priority."), - 'model_id': fields.many2one('ir.model', 'Object', required=True, help="Select the object on which the action will work (read, write, create)."), + 'model_id': fields.many2one('ir.model', 'Object', required=True, help="Select the object on which the action will work (read, write, create).", ondelete='cascade'), 'action_id': fields.many2one('ir.actions.actions', 'Client Action', help="Select the Action Window, Report, Wizard to be executed."), 'trigger_name': fields.selection(_select_signals, string='Trigger Signal', size=128, help="The workflow signal to trigger"), 'wkf_model_id': fields.many2one('ir.model', 'Target Object', help="The object that should receive the workflow signal (must have an associated workflow)"), diff --git a/openerp/addons/base/ir/ir_model.py b/openerp/addons/base/ir/ir_model.py index fdce0d7c483..1af5818438a 100644 --- a/openerp/addons/base/ir/ir_model.py +++ b/openerp/addons/base/ir/ir_model.py @@ -1,8 +1,9 @@ # -*- coding: utf-8 -*- + ############################################################################## # -# OpenERP, Open Source Management Solution -# Copyright (C) 2004-2009 Tiny SPRL (). +# OpenERP, Open Source Business Applications +# Copyright (C) 2004-2012 OpenERP S.A. (). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as @@ -23,20 +24,21 @@ import re import time import types -from osv import fields,osv -import netsvc -from osv.orm import except_orm, browse_record -import tools -from tools.safe_eval import safe_eval as eval -from tools import config -from tools.translate import _ -import pooler +from openerp.osv import fields,osv +from openerp import netsvc, pooler, tools +from openerp.tools.safe_eval import safe_eval as eval +from openerp.tools import config +from openerp.tools.translate import _ +from openerp.osv.orm import except_orm, browse_record, EXT_ID_PREFIX_FK, \ + EXT_ID_PREFIX_M2M_TABLE, EXT_ID_PREFIX_CONSTRAINT _logger = logging.getLogger(__name__) +MODULE_UNINSTALL_FLAG = '_force_unlink' + def _get_fields_type(self, cr, uid, context=None): # Avoid too many nested `if`s below, as RedHat's Python 2.6 - # break on it. See bug 939653. + # break on it. See bug 939653. return sorted([(k,k) for k,v in fields.__dict__.iteritems() if type(v) == types.TypeType and \ issubclass(v, fields._column) and \ @@ -73,7 +75,7 @@ class ir_model(osv.osv): def _search_osv_memory(self, cr, uid, model, name, domain, context=None): if not domain: return [] - field, operator, value = domain[0] + __, operator, value = domain[0] if operator not in ['=', '!=']: raise osv.except_osv(_('Invalid search criterions'), _('The osv_memory field can only be compared with = and != operator.')) value = bool(value) if operator == '=' else not bool(value) @@ -136,13 +138,33 @@ class ir_model(osv.osv): super(ir_model, self).search(cr, uid, domain, limit=limit, context=context), context=context) + def _drop_table(self, cr, uid, ids, context=None): + for model in self.browse(cr, uid, ids, context): + model_pool = self.pool.get(model.model) + cr.execute('select relkind from pg_class where relname=%s', (model_pool._table,)) + result = cr.fetchone() + if result and result[0] == 'v': + cr.execute('DROP view %s' % (model_pool._table,)) + elif result and result[0] == 'r': + cr.execute('DROP TABLE %s' % (model_pool._table,)) + return True def unlink(self, cr, user, ids, context=None): - for model in self.browse(cr, user, ids, context): - if model.state != 'manual': - raise except_orm(_('Error'), _("You can not remove the model '%s' !") %(model.name,)) + # Prevent manual deletion of module tables + if context is None: context = {} + if isinstance(ids, (int, long)): + ids = [ids] + if not context.get(MODULE_UNINSTALL_FLAG) and \ + any(model.state != 'manual' for model in self.browse(cr, user, ids, context)): + raise except_orm(_('Error'), _("Model '%s' contains module data and cannot be removed!") % (model.name,)) + + self._drop_table(cr, user, ids, context) res = super(ir_model, self).unlink(cr, user, ids, context) - pooler.restart_pool(cr.dbname) + if not context.get(MODULE_UNINSTALL_FLAG): + # only reload pool for normal unlink. For module uninstall the + # reload is done independently in openerp.modules.loading + pooler.restart_pool(cr.dbname) + return res def write(self, cr, user, ids, vals, context=None): @@ -266,16 +288,30 @@ class ir_model_fields(osv.osv): ('size_gt_zero', 'CHECK (size>0)',_size_gt_zero_msg ), ] + def _drop_column(self, cr, uid, ids, context=None): + for field in self.browse(cr, uid, ids, context): + model = self.pool.get(field.model) + cr.execute('select relkind from pg_class where relname=%s', (model._table,)) + result = cr.fetchone() + cr.execute("SELECT column_name FROM information_schema.columns WHERE table_name ='%s' and column_name='%s'" %(model._table, field.name)) + column_name = cr.fetchone() + if column_name and (result and result[0] == 'r'): + cr.execute('ALTER table "%s" DROP column "%s" cascade' % (model._table, field.name)) + model._columns.pop(field.name, None) + return True + def unlink(self, cr, user, ids, context=None): - for field in self.browse(cr, user, ids, context): - if field.state <> 'manual': - raise except_orm(_('Error'), _("You cannot remove the field '%s' !") %(field.name,)) - # - # MAY BE ADD A ALTER TABLE DROP ? - # - #Removing _columns entry for that table - self.pool.get(field.model)._columns.pop(field.name,None) - return super(ir_model_fields, self).unlink(cr, user, ids, context) + # 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 except_orm(_('Error'), _("This column contains module data and cannot be removed!")) + + self._drop_column(cr, user, ids, context) + res = super(ir_model_fields, self).unlink(cr, user, ids, context) + return res def create(self, cr, user, vals, context=None): if 'model_id' in vals: @@ -295,7 +331,7 @@ class ir_model_fields(osv.osv): raise except_orm(_('Error'), _("Custom fields must have a name that starts with 'x_' !")) if vals.get('relation',False) and not self.pool.get('ir.model').search(cr, user, [('model','=',vals['relation'])]): - raise except_orm(_('Error'), _("Model %s does not exist!") % vals['relation']) + raise except_orm(_('Error'), _("Model %s does not exist!") % vals['relation']) if self.pool.get(vals['model']): self.pool.get(vals['model']).__init__(self.pool, cr) @@ -414,7 +450,7 @@ class ir_model_fields(osv.osv): ctx = context.copy() ctx.update({'select': vals.get('select_level','0'),'update_custom_fields':True}) - for model_key, patch_struct in models_patch.items(): + for __, patch_struct in models_patch.items(): obj = patch_struct[0] for col_name, col_prop, val in patch_struct[1]: setattr(obj._columns[col_name], col_prop, val) @@ -622,10 +658,10 @@ class ir_model_data(osv.osv): def __init__(self, pool, cr): osv.osv.__init__(self, pool, cr) self.doinit = True - # also stored in pool to avoid being discarded along with this osv instance if getattr(pool, 'model_data_reference_ids', None) is None: self.pool.model_data_reference_ids = {} + self.loads = self.pool.model_data_reference_ids def _auto_init(self, cr, context=None): @@ -670,6 +706,7 @@ class ir_model_data(osv.osv): id = False return id + def unlink(self, cr, uid, ids, context=None): """ Regular unlink method, but make sure to clear the caches. """ self._get_id.clear_cache(self) @@ -680,17 +717,14 @@ class ir_model_data(osv.osv): model_obj = self.pool.get(model) if not context: context = {} - # records created during module install should result in res.log entries that are already read! context = dict(context, res_log_read=True) - if xml_id and ('.' in xml_id): assert len(xml_id.split('.'))==2, _("'%s' contains too many dots. XML ids should not contain dots ! These are used to refer to other modules data, as in module.reference_id") % (xml_id) module, xml_id = xml_id.split('.') if (not xml_id) and (not self.doinit): return False action_id = False - if xml_id: cr.execute('''SELECT imd.id, imd.res_id, md.id, imd.model FROM ir_model_data imd LEFT JOIN %s md ON (imd.res_id = md.id) @@ -794,52 +828,139 @@ class ir_model_data(osv.osv): cr.execute('UPDATE ir_values set value=%s WHERE model=%s and key=%s and name=%s'+where,(value, model, key, name)) return True + def _module_data_uninstall(self, cr, uid, ids, context=None): + """Deletes all the records referenced by the ir.model.data entries + ``ids`` along with their corresponding database backed (including + dropping tables, columns, FKs, etc, as long as there is no other + ir.model.data entry holding a reference to them (which indicates that + they are still owned by another module). + Attempts to perform the deletion in an appropriate order to maximize + the chance of gracefully deleting all records. + This step is performed as part of the full uninstallation of a module. + """ + + if uid != 1 and not self.pool.get('ir.model.access').check_groups(cr, uid, "base.group_system"): + raise except_orm(_('Permission Denied'), (_('Administrator access is required to uninstall a module'))) + + context = dict(context or {}) + context[MODULE_UNINSTALL_FLAG] = True # enable model/field deletion + + ids_set = set(ids) + wkf_todo = [] + to_unlink = [] + to_drop_table = [] + ids.sort() + ids.reverse() + for data in self.browse(cr, uid, ids, context): + model = data.model + res_id = data.res_id + model_obj = self.pool.get(model) + name = tools.ustr(data.name) + + if name.startswith(EXT_ID_PREFIX_FK) or name.startswith(EXT_ID_PREFIX_M2M_TABLE)\ + or name.startswith(EXT_ID_PREFIX_CONSTRAINT): + # double-check we are really going to delete all the owners of this schema element + cr.execute("""SELECT id from ir_model_data where name = %s and res_id IS NULL""", (data.name,)) + external_ids = [x[0] for x in cr.fetchall()] + if (set(external_ids)-ids_set): + # as installed modules have defined this element we must not delete it! + continue + + if name.startswith(EXT_ID_PREFIX_FK): + name = name[len(EXT_ID_PREFIX_FK):] + # test if FK exists on this table (it could be on a related m2m table, in which case we ignore it) + cr.execute("""SELECT 1 from pg_constraint cs JOIN pg_class cl ON (cs.conrelid = cl.oid) + WHERE cs.contype=%s and cs.conname=%s and cl.relname=%s""", ('f', name, model_obj._table)) + if cr.fetchone(): + cr.execute('ALTER TABLE "%s" DROP CONSTRAINT "%s"' % (model_obj._table, name),) + _logger.info('Dropped FK CONSTRAINT %s@%s', name, model) + continue + + if name.startswith(EXT_ID_PREFIX_M2M_TABLE): + name = name[len(EXT_ID_PREFIX_M2M_TABLE):] + cr.execute("SELECT 1 FROM information_schema.tables WHERE table_name=%s", (name,)) + if cr.fetchone() and not name in to_drop_table: + to_drop_table.append(name) + continue + + if name.startswith(EXT_ID_PREFIX_CONSTRAINT): + name = name[len(EXT_ID_PREFIX_CONSTRAINT):] + # test if constraint exists + cr.execute("""SELECT 1 from pg_constraint cs JOIN pg_class cl ON (cs.conrelid = cl.oid) + WHERE cs.contype=%s and cs.conname=%s and cl.relname=%s""", ('u', name, model_obj._table)) + if cr.fetchone(): + cr.execute('ALTER TABLE "%s" DROP CONSTRAINT "%s"' % (model_obj._table, name),) + _logger.info('Dropped CONSTRAINT %s@%s', name, model) + continue + + pair_to_unlink = (model, res_id) + if pair_to_unlink not in to_unlink: + to_unlink.append(pair_to_unlink) + + if model == 'workflow.activity': + # Special treatment for workflow activities: temporarily revert their + # incoming transition and trigger an update to force all workflow items + # to move out before deleting them + cr.execute('select res_type,res_id from wkf_instance where id IN (select inst_id from wkf_workitem where act_id=%s)', (res_id,)) + wkf_todo.extend(cr.fetchall()) + cr.execute("update wkf_transition set condition='True', group_id=NULL, signal=NULL,act_to=act_from,act_from=%s where act_to=%s", (res_id,res_id)) + + wf_service = netsvc.LocalService("workflow") + for model,res_id in wkf_todo: + try: + wf_service.trg_write(uid, model, res_id, cr) + except: + _logger.info('Unable to force processing of workflow for item %s@%s in order to leave activity to be deleted', res_id, model) + + # drop m2m relation tables + for table in to_drop_table: + cr.execute('DROP TABLE %s CASCADE'% (table),) + _logger.info('Dropped table %s', table) + + def unlink_if_refcount(to_unlink): + for model, res_id in to_unlink: + external_ids = self.search(cr, uid, [('model', '=', model),('res_id', '=', res_id)]) + if (set(external_ids)-ids_set): + # if other modules have defined this record, we must not delete it + return + _logger.info('Deleting %s@%s', res_id, model) + try: + self.pool.get(model).unlink(cr, uid, [res_id], context=context) + except: + _logger.info('Unable to delete %s@%s', res_id, model, exc_info=True) + + # Remove non-model records first, then model fields, and finish with models + unlink_if_refcount((model, res_id) for model, res_id in to_unlink + if model not in ('ir.model','ir.model.fields')) + unlink_if_refcount((model, res_id) for model, res_id in to_unlink + if model == 'ir.model.fields') + unlink_if_refcount((model, res_id) for model, res_id in to_unlink + if model == 'ir.model') + + cr.commit() + def _process_end(self, cr, uid, modules): """ Clear records removed from updated module data. - This method is called at the end of the module loading process. It is meant to removed records that are no longer present in the updated data. Such records are recognised as the one with an xml id and a module in ir_model_data and noupdate set to false, but not present in self.loads. - """ if not modules: return True - modules = list(modules) - module_in = ",".join(["%s"] * len(modules)) - cr.execute('select id,name,model,res_id,module from ir_model_data where module IN (' + module_in + ') and noupdate=%s', modules + [False]) - wkf_todo = [] to_unlink = [] - for (id, name, model, res_id,module) in cr.fetchall(): + cr.execute("""SELECT id,name,model,res_id,module FROM ir_model_data + WHERE module IN %s AND res_id IS NOT NULL AND noupdate=%s""", + (tuple(modules), False)) + for (id, name, model, res_id, module) in cr.fetchall(): if (module,name) not in self.loads: to_unlink.append((model,res_id)) - if model=='workflow.activity': - cr.execute('select res_type,res_id from wkf_instance where id IN (select inst_id from wkf_workitem where act_id=%s)', (res_id,)) - wkf_todo.extend(cr.fetchall()) - cr.execute("update wkf_transition set condition='True', group_id=NULL, signal=NULL,act_to=act_from,act_from=%s where act_to=%s", (res_id,res_id)) - cr.execute("delete from wkf_transition where act_to=%s", (res_id,)) - - for model,id in wkf_todo: - wf_service = netsvc.LocalService("workflow") - wf_service.trg_write(uid, model, id, cr) - - cr.commit() if not config.get('import_partial'): for (model, res_id) in to_unlink: if self.pool.get(model): _logger.info('Deleting %s@%s', res_id, model) - try: - self.pool.get(model).unlink(cr, uid, [res_id]) - cr.commit() - except Exception: - cr.rollback() - _logger.warning( - 'Could not delete obsolete record with id: %d of model %s\n' - 'There should be some relation that points to this resource\n' - 'You should manually fix this and restart with --update=module', - res_id, model) - return True -ir_model_data() + self.pool.get(model).unlink(cr, uid, [res_id]) + # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: diff --git a/openerp/addons/base/ir/workflow/workflow.py b/openerp/addons/base/ir/workflow/workflow.py index edd070ae50d..925d4700663 100644 --- a/openerp/addons/base/ir/workflow/workflow.py +++ b/openerp/addons/base/ir/workflow/workflow.py @@ -1,8 +1,8 @@ # -*- coding: utf-8 -*- ############################################################################## -# -# OpenERP, Open Source Management Solution -# Copyright (C) 2004-2009 Tiny SPRL (). +# +# OpenERP, Open Source Business Applications +# Copyright (C) 2004-2012 OpenERP S.A. (). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as @@ -15,19 +15,18 @@ # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License -# along with this program. If not, see . +# along with this program. If not, see . # ############################################################################## -from osv import fields, osv -from tools import graph -import netsvc +from openerp.osv import fields, osv +from openerp.tools.translate import _ +from openerp import netsvc class workflow(osv.osv): _name = "workflow" _table = "wkf" _order = "name" - # _log_access = False _columns = { 'name': fields.char('Name', size=64, required=True), 'osv': fields.char('Resource Object', size=64, required=True,select=True), @@ -46,78 +45,33 @@ class workflow(osv.osv): return super(workflow, self).write(cr, user, ids, vals, context=context) def get_active_workitems(self, cr, uid, res, res_id, context=None): - cr.execute('select * from wkf where osv=%s limit 1',(res,)) wkfinfo = cr.dictfetchone() workitems = [] - if wkfinfo: cr.execute('SELECT id FROM wkf_instance \ WHERE res_id=%s AND wkf_id=%s \ ORDER BY state LIMIT 1', (res_id, wkfinfo['id'])) inst_id = cr.fetchone() - + cr.execute('select act_id,count(*) from wkf_workitem where inst_id=%s group by act_id', (inst_id,)) - workitems = dict(cr.fetchall()) - + workitems = dict(cr.fetchall()) return {'wkf': wkfinfo, 'workitems': workitems} - - # - # scale = (vertical-distance, horizontal-distance, min-node-width(optional), min-node-height(optional), margin(default=20)) - # - - -# def graph_get(self, cr, uid, id, scale, context={}): -# -# nodes= [] -# nodes_name = [] -# transitions = [] -# start = [] -# tres = {} -# no_ancester = [] -# workflow = self.browse(cr, uid, id, context) -# for a in workflow.activities: -# nodes_name.append((a.id,a.name)) -# nodes.append(a.id) -# if a.flow_start: -# start.append(a.id) -# else: -# if not a.in_transitions: -# no_ancester.append(a.id) -# -# for t in a.out_transitions: -# transitions.append((a.id, t.act_to.id)) -# tres[t.id] = (a.id, t.act_to.id) -# -# -# g = graph(nodes, transitions, no_ancester) -# g.process(start) -# g.scale(*scale) -# result = g.result_get() -# results = {} -# -# for node in nodes_name: -# results[str(node[0])] = result[node[0]] -# results[str(node[0])]['name'] = node[1] -# -# return {'nodes': results, 'transitions': tres} - - def create(self, cr, user, vals, context=None): if not context: context={} wf_service = netsvc.LocalService("workflow") wf_service.clear_cache(cr, user) return super(workflow, self).create(cr, user, vals, context=context) + workflow() class wkf_activity(osv.osv): _name = "workflow.activity" _table = "wkf_activity" _order = "name" - # _log_access = False _columns = { 'name': fields.char('Name', size=64, required=True), 'wkf_id': fields.many2one('workflow', 'Workflow', required=True, select=True, ondelete='cascade'), @@ -138,22 +92,29 @@ class wkf_activity(osv.osv): 'join_mode': lambda *a: 'XOR', 'split_mode': lambda *a: 'XOR', } + + def unlink(self, cr, uid, ids, context=None): + if context is None: context = {} + if not context.get('_force_unlink') and self.pool.get('workflow.workitem').search(cr, uid, [('act_id', 'in', ids)]): + raise osv.except_osv(_('Operation forbidden'), + _('Please make sure no workitems refer to an activity before deleting it!')) + super(wkf_activity, self).unlink(cr, uid, ids, context=context) + wkf_activity() class wkf_transition(osv.osv): _table = "wkf_transition" _name = "workflow.transition" - # _log_access = False _rec_name = 'signal' _columns = { 'trigger_model': fields.char('Trigger Object', size=128), 'trigger_expr_id': fields.char('Trigger Expression', size=128), - 'signal': fields.char('Signal (button Name)', size=64, + 'signal': fields.char('Signal (button Name)', size=64, help="When the operation of transition comes from a button pressed in the client form, "\ "signal tests the name of the pressed button. If signal is NULL, no button is necessary to validate this transition."), - 'group_id': fields.many2one('res.groups', 'Group Required', + 'group_id': fields.many2one('res.groups', 'Group Required', help="The group that a user must have to be authorized to validate this transition."), - 'condition': fields.char('Condition', required=True, size=128, + 'condition': fields.char('Condition', required=True, size=128, help="Expression to be satisfied if we want the transition done."), 'act_from': fields.many2one('workflow.activity', 'Source Activity', required=True, select=True, ondelete='cascade', help="Source activity. When this activity is over, the condition is tested to determine if we can start the ACT_TO activity."), @@ -194,7 +155,7 @@ class wkf_workitem(osv.osv): _log_access = False _rec_name = 'state' _columns = { - 'act_id': fields.many2one('workflow.activity', 'Activity', required=True, ondelete="restrict", select=True), + 'act_id': fields.many2one('workflow.activity', 'Activity', required=True, ondelete="cascade", select=True), 'wkf_id': fields.related('act_id','wkf_id', type='many2one', relation='workflow', string='Workflow'), 'subflow_id': fields.many2one('workflow.instance', 'Subflow', ondelete="cascade", select=True), 'inst_id': fields.many2one('workflow.instance', 'Instance', required=True, ondelete="cascade", select=True), diff --git a/openerp/addons/base/module/module.py b/openerp/addons/base/module/module.py index cb484520058..acf22923d14 100644 --- a/openerp/addons/base/module/module.py +++ b/openerp/addons/base/module/module.py @@ -2,8 +2,7 @@ ############################################################################## # # OpenERP, Open Source Management Solution -# Copyright (C) 2004-2009 Tiny SPRL (). -# Copyright (C) 2010 OpenERP s.a. (). +# Copyright (C) 2004-2012 OpenERP S.A. (). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as @@ -19,26 +18,16 @@ # along with this program. If not, see . # ############################################################################## -import base64 -import cStringIO import imp import logging -import os import re -import StringIO import urllib -import zipfile import zipimport -import openerp.modules as addons -import pooler -import release -import tools - -from tools.parse_version import parse_version -from tools.translate import _ - -from osv import fields, osv, orm +from openerp import modules, pooler, release, tools +from openerp.tools.parse_version import parse_version +from openerp.tools.translate import _ +from openerp.osv import fields, osv, orm _logger = logging.getLogger(__name__) @@ -95,7 +84,7 @@ class module(osv.osv): def get_module_info(cls, name): info = {} try: - info = addons.load_information_from_description_file(name) + info = modules.load_information_from_description_file(name) info['version'] = release.major_version + '.' + info['version'] except Exception: _logger.debug('Error when trying to fetch informations for ' @@ -123,7 +112,7 @@ class module(osv.osv): if field_name is None or 'menus_by_module' in field_name: dmodels.append('ir.ui.menu') assert dmodels, "no models for %s" % field_name - + for module_rec in self.browse(cr, uid, ids, context=context): res[module_rec.id] = { 'menus_by_module': [], @@ -165,7 +154,7 @@ class module(osv.osv): except Exception, e: _logger.warning('Unknown error while fetching data of %s', module_rec.name, exc_info=True) - for key, value in res.iteritems(): + for key, _ in res.iteritems(): for k, v in res[key].iteritems(): res[key][k] = "\n".join(sorted(v)) return res @@ -184,7 +173,7 @@ class module(osv.osv): # installed_version refer the latest version (the one on disk) # latest_version refer the installed version (the one in database) # published_version refer the version available on the repository - 'installed_version': fields.function(_get_latest_version, + 'installed_version': fields.function(_get_latest_version, string='Latest version', type='char'), 'latest_version': fields.char('Installed version', size=64, readonly=True), 'published_version': fields.char('Published Version', size=64, readonly=True), @@ -276,7 +265,7 @@ class module(osv.osv): while parts: part = parts.pop() try: - f, path, descr = imp.find_module(part, path and [path] or None) + _, path, _ = imp.find_module(part, path and [path] or None) except ImportError: raise ImportError('No module named %s' % (pydep,)) @@ -343,7 +332,6 @@ class module(osv.osv): # Mark them to be installed. if to_install_ids: self.button_install(cr, uid, to_install_ids, context=context) - return dict(ACTION_DICT, name=_('Install')) def button_immediate_install(self, cr, uid, ids, context=None): @@ -356,7 +344,7 @@ class module(osv.osv): """ self.button_install(cr, uid, ids, context=context) cr.commit() - db, pool = pooler.restart_pool(cr.dbname, update_module=True) + _, pool = pooler.restart_pool(cr.dbname, update_module=True) config = pool.get('res.config').next(cr, uid, [], context=context) or {} if config.get('type') not in ('ir.actions.reload', 'ir.actions.act_window_close'): @@ -376,20 +364,49 @@ class module(osv.osv): self.write(cr, uid, ids, {'state': 'uninstalled', 'demo':False}) return True + def module_uninstall(self, cr, uid, ids, context=None): + """Perform the various steps required to uninstall a module completely + including the deletion of all database structures created by the module: + tables, columns, constraints, etc.""" + ir_model_data = self.pool.get('ir.model.data') + modules_to_remove = [m.name for m in self.browse(cr, uid, ids, context)] + data_ids = ir_model_data.search(cr, uid, [('module', 'in', modules_to_remove)]) + ir_model_data._module_data_uninstall(cr, uid, data_ids, context) + ir_model_data.unlink(cr, uid, data_ids, context) + self.write(cr, uid, ids, {'state': 'uninstalled'}) + return True + + def downstream_dependencies(self, cr, uid, ids, known_dep_ids=None, + exclude_states=['uninstalled','uninstallable','to remove'], + context=None): + """Return the ids of all modules that directly or indirectly depend + on the given module `ids`, and that satisfy the `exclude_states` + filter""" + if not ids: return [] + known_dep_ids = set(known_dep_ids or []) + cr.execute('''SELECT DISTINCT m.id + FROM + ir_module_module_dependency d + JOIN + ir_module_module m ON (d.module_id=m.id) + WHERE + d.name IN (SELECT name from ir_module_module where id in %s) AND + m.state NOT IN %s AND + m.id NOT IN %s ''', + (tuple(ids),tuple(exclude_states), tuple(known_dep_ids or ids))) + new_dep_ids = set([m[0] for m in cr.fetchall()]) + missing_mod_ids = new_dep_ids - known_dep_ids + known_dep_ids |= new_dep_ids + if missing_mod_ids: + known_dep_ids |= set(self.downstream_dependencies(cr, uid, list(missing_mod_ids), + known_dep_ids, exclude_states,context)) + return list(known_dep_ids) + def button_uninstall(self, cr, uid, ids, context=None): - for module in self.browse(cr, uid, ids): - cr.execute('''select m.state,m.name - from - ir_module_module_dependency d - join - ir_module_module m on (d.module_id=m.id) - where - d.name=%s and - m.state not in ('uninstalled','uninstallable','to remove')''', (module.name,)) - res = cr.fetchall() - if res: - raise orm.except_orm(_('Error'), _('Some installed modules depend on the module you plan to Uninstall :\n %s') % '\n'.join(map(lambda x: '\t%s: %s' % (x[0], x[1]), res))) - self.write(cr, uid, ids, {'state': 'to remove'}) + if any(m.name == 'base' for m in self.browse(cr, uid, ids)): + raise orm.except_orm(_('Error'), _("The `base` module cannot be uninstalled")) + dep_ids = self.downstream_dependencies(cr, uid, ids, context=context) + self.write(cr, uid, ids + dep_ids, {'state': 'to remove'}) return dict(ACTION_DICT, name=_('Uninstall')) def button_uninstall_cancel(self, cr, uid, ids, context=None): @@ -463,7 +480,7 @@ class module(osv.osv): known_mods_names = dict([(m.name, m) for m in known_mods]) # iterate through detected modules and update/create them in db - for mod_name in addons.get_modules(): + for mod_name in modules.get_modules(): mod = known_mods_names.get(mod_name) terp = self.get_module_info(mod_name) values = self.get_values_from_terp(terp) @@ -472,7 +489,7 @@ class module(osv.osv): updated_values = {} for key in values: old = getattr(mod, key) - updated = isinstance(values[key], basestring) and tools.ustr(values[key]) or values[key] + updated = isinstance(values[key], basestring) and tools.ustr(values[key]) or values[key] if not old == updated: updated_values[key] = values[key] if terp.get('installable', True) and mod.state == 'uninstallable': @@ -482,7 +499,7 @@ class module(osv.osv): if updated_values: self.write(cr, uid, mod.id, updated_values) else: - mod_path = addons.get_module_path(mod_name) + mod_path = modules.get_module_path(mod_name) if not mod_path: continue if not terp or not terp.get('installable', True): @@ -511,7 +528,7 @@ class module(osv.osv): if not download: continue zip_content = urllib.urlopen(mod.url).read() - fname = addons.get_module_path(str(mod.name)+'.zip', downloaded=True) + fname = modules.get_module_path(str(mod.name)+'.zip', downloaded=True) try: with open(fname, 'wb') as fp: fp.write(zip_content) @@ -581,17 +598,17 @@ class module(osv.osv): for mod in self.browse(cr, uid, ids): if mod.state != 'installed': continue - modpath = addons.get_module_path(mod.name) + modpath = modules.get_module_path(mod.name) if not modpath: # unable to find the module. we skip continue for lang in filter_lang: iso_lang = tools.get_iso_codes(lang) - f = addons.get_module_resource(mod.name, 'i18n', iso_lang + '.po') + f = modules.get_module_resource(mod.name, 'i18n', iso_lang + '.po') context2 = context and context.copy() or {} if f and '_' in iso_lang: iso_lang2 = iso_lang.split('_')[0] - f2 = addons.get_module_resource(mod.name, 'i18n', iso_lang2 + '.po') + f2 = modules.get_module_resource(mod.name, 'i18n', iso_lang2 + '.po') if f2: _logger.info('module %s: loading base translation file %s for language %s', mod.name, iso_lang2, lang) tools.trans_load(cr, f2, lang, verbose=False, context=context) @@ -601,7 +618,7 @@ class module(osv.osv): # like "en". if (not f) and '_' in iso_lang: iso_lang = iso_lang.split('_')[0] - f = addons.get_module_resource(mod.name, 'i18n', iso_lang + '.po') + f = modules.get_module_resource(mod.name, 'i18n', iso_lang + '.po') if f: _logger.info('module %s: loading translation file (%s) for language %s', mod.name, iso_lang, lang) tools.trans_load(cr, f, lang, verbose=False, context=context2) @@ -660,8 +677,12 @@ class module_dependency(osv.osv): return result _columns = { + # The dependency name 'name': fields.char('Name', size=128, select=True), + + # The module that depends on it 'module_id': fields.many2one('ir.module.module', 'Module', select=True, ondelete='cascade'), + 'state': fields.function(_state, type='selection', selection=[ ('uninstallable','Uninstallable'), ('uninstalled','Not Installed'), diff --git a/openerp/addons/base/module/module_view.xml b/openerp/addons/base/module/module_view.xml index c1361401414..0005aee98ff 100644 --- a/openerp/addons/base/module/module_view.xml +++ b/openerp/addons/base/module/module_view.xml @@ -153,7 +153,9 @@