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
32 from psycopg2 import IntegrityError
33 from netsvc import Logger, LOG_ERROR
34 from tools.misc import UpdateableDict
36 from tools.translate import _
39 module_class_list = {}
43 class except_osv(Exception):
44 def __init__(self, name, value, exc_type='warning'):
46 self.exc_type = exc_type
48 self.args = (exc_type, name)
51 from tools.func import wraps
52 class osv_pool(netsvc.Service):
56 def wrapper(self, dbname, *args, **kwargs):
58 if not pooler.get_pool(dbname)._ready:
59 raise except_osv('Database not ready', 'Currently, this database is not fully loaded and can not be used.')
60 return f(self, dbname, *args, **kwargs)
61 except orm.except_orm, inst:
62 self.abortResponse(1, inst.name, 'warning', inst.value)
63 except except_osv, inst:
64 self.abortResponse(1, inst.name, inst.exc_type, inst.value)
65 except IntegrityError, inst:
66 for key in self._sql_error.keys():
68 self.abortResponse(1, _('Constraint Error'), 'warning', _(self._sql_error[key]))
69 self.abortResponse(1, 'Integrity Error', 'warning', inst[0])
72 tb_s = "".join(traceback.format_exception(*sys.exc_info()))
74 logger.notifyChannel('web-services', LOG_ERROR, tb_s)
83 self.module_object_list = {}
86 self._store_function = {}
88 self._init_parent = {}
89 netsvc.Service.__init__(self, 'object_proxy', audience='')
90 self.exportMethod(self.obj_list)
91 self.exportMethod(self.exec_workflow)
92 self.exportMethod(self.execute)
94 def init_set(self, cr, mode):
95 different = mode != self._init
98 self._init_parent = {}
100 for o in self._init_parent:
101 self.get(o)._parent_store_compute(cr)
107 def execute_cr(self, cr, uid, obj, method, *args, **kw):
108 object = pooler.get_pool(cr.dbname).get(obj)
110 raise except_osv('Object Error', 'Object %s doesn\'t exist' % str(obj))
111 return getattr(object, method)(cr, uid, *args, **kw)
114 def execute(self, db, uid, obj, method, *args, **kw):
115 db, pool = pooler.get_db_and_pool(db)
119 res = pool.execute_cr(cr, uid, obj, method, *args, **kw)
128 def exec_workflow_cr(self, cr, uid, obj, method, *args):
129 wf_service = netsvc.LocalService("workflow")
130 return wf_service.trg_validate(uid, obj, args[0], method, cr)
133 def exec_workflow(self, db, uid, obj, method, *args):
134 cr = pooler.get_db(db).cursor()
137 res = self.exec_workflow_cr(cr, uid, obj, method, *args)
147 return self.obj_pool.keys()
149 # adds a new object instance to the object pool.
150 # if it already existed, the instance is replaced
151 def add(self, name, obj_inst):
152 if name in self.obj_pool:
153 del self.obj_pool[name]
154 self.obj_pool[name] = obj_inst
156 module = str(obj_inst.__class__)[6:]
157 module = module[:len(module)-1]
158 module = module.split('.')[0][2:]
159 self.module_object_list.setdefault(module, []).append(obj_inst)
161 # Return None if object does not exist
163 obj = self.obj_pool.get(name, None)
166 #TODO: pass a list of modules to load
167 def instanciate(self, module, cr):
169 class_list = module_class_list.get(module, [])
170 for klass in class_list:
171 res.append(klass.createInstance(self, module, cr))
175 class osv_memory(orm.orm_memory):
176 #__metaclass__ = inheritor
178 module = str(cls)[6:]
179 module = module[:len(module)-1]
180 module = module.split('.')[0][2:]
181 if not hasattr(cls, '_module'):
183 module_class_list.setdefault(cls._module, []).append(cls)
184 class_pool[cls._name] = cls
185 if module not in module_list:
186 module_list.append(cls._module)
190 # Goal: try to apply inheritancy at the instanciation level and
191 # put objects in the pool var
193 def createInstance(cls, pool, module, cr):
194 name = hasattr(cls, '_name') and cls._name or cls._inherit
195 parent_names = hasattr(cls, '_inherit') and cls._inherit
197 for parent_name in ((type(parent_names)==list) and parent_names or [parent_names]):
198 parent_class = pool.get(parent_name).__class__
199 assert pool.get(parent_name), "parent class %s does not exist in module %s !" % (parent_name, module)
201 for s in ('_columns', '_defaults'):
202 new = copy.copy(getattr(pool.get(parent_name), s))
203 if hasattr(new, 'update'):
204 new.update(cls.__dict__.get(s, {}))
206 new.extend(cls.__dict__.get(s, []))
208 name = hasattr(cls, '_name') and cls._name or cls._inherit
209 cls = type(name, (cls, parent_class), nattr)
211 obj = object.__new__(cls)
212 obj.__init__(pool, cr)
214 createInstance = classmethod(createInstance)
216 def __init__(self, pool, cr):
217 pool.add(self._name, self)
219 orm.orm_memory.__init__(self, cr)
224 #__metaclass__ = inheritor
226 module = str(cls)[6:]
227 module = module[:len(module)-1]
228 module = module.split('.')[0][2:]
229 if not hasattr(cls, '_module'):
231 module_class_list.setdefault(cls._module, []).append(cls)
232 class_pool[cls._name] = cls
233 if module not in module_list:
234 module_list.append(cls._module)
238 # Goal: try to apply inheritancy at the instanciation level and
239 # put objects in the pool var
241 def createInstance(cls, pool, module, cr):
242 parent_names = hasattr(cls, '_inherit') and cls._inherit
244 for parent_name in ((type(parent_names)==list) and parent_names or [parent_names]):
245 parent_class = pool.get(parent_name).__class__
246 assert pool.get(parent_name), "parent class %s does not exist in module %s !" % (parent_name, module)
248 for s in ('_columns', '_defaults', '_inherits', '_constraints', '_sql_constraints'):
249 new = copy.copy(getattr(pool.get(parent_name), s))
250 if hasattr(new, 'update'):
251 new.update(cls.__dict__.get(s, {}))
253 if s=='_constraints':
254 for c in cls.__dict__.get(s, []):
256 for c2 in range(len(new)):
264 new.extend(cls.__dict__.get(s, []))
266 name = hasattr(cls, '_name') and cls._name or cls._inherit
267 cls = type(name, (cls, parent_class), nattr)
268 obj = object.__new__(cls)
269 obj.__init__(pool, cr)
271 createInstance = classmethod(createInstance)
273 def __init__(self, pool, cr):
274 pool.add(self._name, self)
276 orm.orm.__init__(self, cr)
278 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: