1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU Affero General Public License as
9 # published by the Free Software Foundation, either version 3 of the
10 # License, or (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU Affero General Public License for more details.
17 # You should have received a copy of the GNU Affero General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
20 ##############################################################################
23 # OSV: Objects Services
29 import openerp.netsvc as netsvc
30 import openerp.pooler as pooler
31 import openerp.sql_db as sql_db
34 from psycopg2 import IntegrityError, errorcodes
35 from openerp.tools.func import wraps
36 from openerp.tools.translate import translate
39 class except_osv(Exception):
40 def __init__(self, name, value, exc_type='warning'):
42 self.exc_type = exc_type
44 self.args = (exc_type, name)
47 class object_proxy(netsvc.Service):
49 self.logger = logging.getLogger('web-services')
50 netsvc.Service.__init__(self, 'object_proxy', audience='')
51 self.exportMethod(self.exec_workflow)
52 self.exportMethod(self.execute)
56 def wrapper(self, dbname, *args, **kwargs):
57 """ Wraps around OSV functions and normalises a few exceptions
61 # We try to do the same as the _(), but without the frame
62 # inspection, since we aready are wrapping an osv function
63 # trans_obj = self.get('ir.translation') cannot work yet :(
66 if args and isinstance(args[-1], dict):
68 elif isinstance(kwargs, dict):
69 ctx = kwargs.get('context', {})
72 if args and isinstance(args[0], (long, int)):
75 lang = ctx and ctx.get('lang')
76 if not (lang or hasattr(src, '__call__')):
79 # We open a *new* cursor here, one reason is that failed SQL
80 # queries (as in IntegrityError) will invalidate the current one.
83 if hasattr(src, '__call__'):
84 # callable. We need to find the right parameters to call
85 # the orm._sql_message(self, cr, uid, ids, context) function,
87 # our signature is f(osv_pool, dbname [,uid, obj, method, args])
89 if args and len(args) > 1:
90 obj = self.get(args[1])
91 if len(args) > 3 and isinstance(args[3], (long, int, list)):
95 cr = sql_db.db_connect(db_name).cursor()
96 return src(obj, cr, uid, ids, context=(ctx or {}))
102 return False # so that the original SQL error will
103 # be returned, it is the best we have.
106 cr = sql_db.db_connect(db_name).cursor()
107 res = translate(cr, name=False, source_type=ttype,
108 lang=lang, source=src)
117 return tr(src, 'code')
120 if pooler.get_pool(dbname)._init:
121 raise except_osv('Database not ready', 'Currently, this database is not fully loaded and can not be used.')
122 return f(self, dbname, *args, **kwargs)
123 except orm.except_orm, inst:
124 if inst.name == 'AccessError':
125 self.logger.debug("AccessError", exc_info=True)
126 self.abortResponse(1, inst.name, 'warning', inst.value)
127 except except_osv, inst:
128 self.abortResponse(1, inst.name, inst.exc_type, inst.value)
129 except IntegrityError, inst:
130 osv_pool = pooler.get_pool(dbname)
131 for key in osv_pool._sql_error.keys():
133 self.abortResponse(1, _('Constraint Error'), 'warning',
134 tr(osv_pool._sql_error[key], 'sql_constraint') or inst[0])
135 if inst.pgcode in (errorcodes.NOT_NULL_VIOLATION, errorcodes.FOREIGN_KEY_VIOLATION, errorcodes.RESTRICT_VIOLATION):
136 msg = _('The operation cannot be completed, probably due to the following:\n- deletion: you may be trying to delete a record while other records still reference it\n- creation/update: a mandatory field is not correctly set')
137 self.logger.debug("IntegrityError", exc_info=True)
139 errortxt = inst.pgerror.replace('«','"').replace('»','"')
140 if '"public".' in errortxt:
141 context = errortxt.split('"public".')[1]
142 model_name = table = context.split('"')[1]
144 last_quote_end = errortxt.rfind('"')
145 last_quote_begin = errortxt.rfind('"', 0, last_quote_end)
146 model_name = table = errortxt[last_quote_begin+1:last_quote_end].strip()
147 model = table.replace("_",".")
148 model_obj = osv_pool.get(model)
150 model_name = model_obj._description or model_obj._name
151 msg += _('\n\n[object with reference: %s - %s]') % (model_name, model)
154 self.abortResponse(1, _('Integrity Error'), 'warning', msg)
156 self.abortResponse(1, _('Integrity Error'), 'warning', inst[0])
158 self.logger.exception("Uncaught exception")
163 def execute_cr(self, cr, uid, obj, method, *args, **kw):
164 object = pooler.get_pool(cr.dbname).get(obj)
166 raise except_osv('Object Error', 'Object %s doesn\'t exist' % str(obj))
167 return getattr(object, method)(cr, uid, *args, **kw)
170 def execute(self, db, uid, obj, method, *args, **kw):
171 cr = pooler.get_db(db).cursor()
174 if method.startswith('_'):
175 raise except_osv('Access Denied', 'Private methods (such as %s) cannot be called remotely.' % (method,))
176 res = self.execute_cr(cr, uid, obj, method, *args, **kw)
178 self.logger.warning('The method %s of the object %s can not return `None` !', method, obj)
187 def exec_workflow_cr(self, cr, uid, obj, method, *args):
188 wf_service = netsvc.LocalService("workflow")
189 return wf_service.trg_validate(uid, obj, args[0], method, cr)
192 def exec_workflow(self, db, uid, obj, method, *args):
193 cr = pooler.get_db(db).cursor()
196 res = self.exec_workflow_cr(cr, uid, obj, method, *args)
206 class osv_memory(orm.orm_memory):
207 """ Deprecated class. """
212 """ Deprecated class. """
216 def start_object_proxy():
219 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: