1 ##############################################################################
3 # Copyright (c) 2004-2006 TINY SPRL. (http://tiny.be) All Rights Reserved.
4 # Fabien Pinckaers <fp@tiny.Be>
6 # WARNING: This program as such is intended to be used by professional
7 # programmers who take the whole responsability of assessing all potential
8 # consequences resulting from its eventual inadequacies and bugs
9 # End users who are looking for a ready-to-use solution with commercial
10 # garantees and support are strongly adviced to contract a Free Software
13 # This program is Free Software; you can redistribute it and/or
14 # modify it under the terms of the GNU General Public License
15 # as published by the Free Software Foundation; either version 2
16 # of the License, or (at your option) any later version.
18 # This program is distributed in the hope that it will be useful,
19 # but WITHOUT ANY WARRANTY; without even the implied warranty of
20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 # GNU General Public License for more details.
23 # You should have received a copy of the GNU General Public License
24 # along with this program; if not, write to the Free Software
25 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
27 ##############################################################################
30 # OSV: Objects Services
41 module_class_list = {}
44 class except_osv(Exception):
45 def __init__(self, name, value, exc_type='warning'):
47 self.exc_type = exc_type
49 self.args = (exc_type,name)
51 class osv_pool(netsvc.Service):
55 self.module_object_list = {}
58 netsvc.Service.__init__(self, 'object_proxy', audience='')
59 self.joinGroup('web-services')
60 self.exportMethod(self.exportedMethods)
61 self.exportMethod(self.obj_list)
62 self.exportMethod(self.exec_workflow)
63 self.exportMethod(self.execute)
64 self.exportMethod(self.execute_cr)
66 def execute_cr(self, cr, uid, obj, method, *args, **kw):
68 # TODO: check security level
71 if (not method in getattr(self.obj_pool[obj],'_protected')) and len(args) and args[0] and len(self.obj_pool[obj]._inherits):
72 types = {obj: args[0]}
73 cr.execute('select inst_type,inst_id,obj_id from inherit where obj_type=%s and obj_id in ('+','.join(map(str,args[0]))+')', (obj,))
74 for ty,id,id2 in cr.fetchall():
78 types[obj].remove(id2)
79 for t,ids in types.items():
82 res = getattr(t,method)(cr, uid, ids, *args[1:], **kw)
84 obj = self.obj_pool[obj]
85 res = getattr(obj,method)(cr, uid, *args, **kw)
87 except orm.except_orm, inst:
88 #self.abortResponse(1, inst.value[0], inst.name, inst.value[1])
89 self.abortResponse(1, inst.value[0], 'warning', inst.value[1])
90 except except_osv, inst:
91 self.abortResponse(1, inst.name, inst.exc_type, inst.value)
92 except psycopg.IntegrityError, inst:
93 for key in self._sql_error.keys():
95 self.abortResponse(1, 'Constraint Error', 'warning', self._sql_error[key])
96 self.abortResponse(1, 'Integrity Error', 'warning', inst[0])
99 def execute(self, db, uid, obj, method, *args, **kw):
100 db, pool = pooler.get_db_and_pool(db)
104 res = pool.execute_cr(cr, uid, obj, method, *args, **kw)
113 def exec_workflow_cr(self, cr, uid, obj, method, *args):
114 wf_service = netsvc.LocalService("workflow")
115 wf_service.trg_validate(uid, obj, args[0], method, cr)
118 def exec_workflow(self, db, uid, obj, method, *args):
119 cr = pooler.get_db(db).cursor()
122 res = self.exec_workflow_cr(cr, uid, obj, method, *args)
132 return self.obj_pool.keys()
134 # adds a new object instance to the object pool.
135 # if it already existed, the instance is replaced
136 def add(self, name, obj_inst):
137 if self.obj_pool.has_key(name):
138 del self.obj_pool[name]
139 self.obj_pool[name] = obj_inst
141 module = str(obj_inst.__class__)[6:]
142 module = module[:len(module)-1]
143 module = module.split('.')[0][2:]
144 self.module_object_list.setdefault(module, []).append(obj_inst)
147 obj = self.obj_pool.get(name, None)
148 # We cannot uncomment this line because it breaks initialisation since objects do not initialize
149 # in the correct order and the ORM doesnt support correctly when some objets do not exist yet
150 # assert obj, "object %s does not exist !" % name
153 #TODO: pass a list of modules to load
154 def instanciate(self, module):
155 # print "module list:", module_list
156 # for module in module_list:
158 class_list = module_class_list.get(module, [])
159 # if module not in self.module_object_list:
160 # print "%s class_list:" % module, class_list
161 for klass in class_list:
162 res.append(klass.createInstance(self, module))
165 # print "skipping module", module
167 #pooler.get_pool(cr.dbname) = osv_pool()
170 # See if we can use the pool var instead of the class_pool one
172 class inheritor(type):
173 def __new__(cls, name, bases, d):
174 parent_name = d.get('_inherit', None)
176 parent_class = class_pool.get(parent_name)
177 assert parent_class, "parent class %s does not exist !" % parent_name
178 for s in ('_columns', '_defaults', '_inherits'):
179 new_dict = copy.copy(getattr(parent_class, s))
180 new_dict.update(d.get(s, {}))
182 bases = (parent_class,)
183 res = type.__new__(cls, name, bases, d)
185 # update _inherits of others objects
192 #__metaclass__ = inheritor
195 if not hasattr(cls, '_module'):
196 module = str(cls)[6:]
197 module = module[:len(module)-1]
198 module = module.split('.')[0][2:]
200 module_class_list.setdefault(cls._module, []).append(cls)
201 class_pool[cls._name] = cls
202 if module not in module_list:
203 module_list.append(cls._module)
207 # Goal: try to apply inheritancy at the instanciation level and
208 # put objects in the pool var
210 def createInstance(cls, pool, module):
212 parent_name = hasattr(cls, '_inherit') and cls._inherit
214 parent_class = pool.get(parent_name).__class__
215 assert parent_class, "parent class %s does not exist !" % parent_name
217 for s in ('_columns', '_defaults', '_inherits'):
218 new_dict = copy.copy(getattr(pool.get(parent_name), s))
219 new_dict.update(cls.__dict__.get(s, {}))
221 #bases = (parent_class,)
222 #obj.__class__ += (parent_class,)
223 #res = type.__new__(cls, name, bases, d)
224 name = hasattr(cls,'_name') and cls._name or cls._inherit
226 cls = type(name, (cls, parent_class), ndict)
228 obj = object.__new__(cls)
231 # return object.__new__(cls, pool)
232 createInstance = classmethod(createInstance)
234 def __init__(self, pool):
235 # print "__init__", self._name, pool
236 pool.add(self._name, self)
238 orm.orm.__init__(self)
240 # pooler.get_pool(cr.dbname).add(self._name, self)
241 # print self._name, module
243 class Cacheable(object):
248 def __delete_key(self, key):
250 for key_item in key[:-1]:
251 odico = odico[key_item]
254 def __add_key(self, key, value):
256 for key_item in key[:-1]:
257 odico = odico.setdefault(key_item, {})
258 odico[key[-1]] = value
260 def add(self, key, value):
261 self.__add_key(key, value)
263 def invalidate(self, key):
264 self.__delete_key(key)
277 def filter_dict(d, fields):
279 for f in fields + ['id']:
284 class cacheable_osv(osv, Cacheable):
289 super(cacheable_osv, self).__init__()
291 def read(self, cr, user, ids, fields=[], context={}, load='_classic_read'):
292 fields = fields or self._columns.keys()
293 ctx = [context.get(x, False) for x in self._relevant]
294 result, tofetch = [], []
296 res = self.get(self._name, id, ctx)
300 result.append(filter_dict(res, fields))
302 # gen the list of "local" (ie not inherited) fields which are classic or many2one
303 nfields = filter(lambda x: x[1]._classic_write, self._columns.items())
304 # gen the list of inherited fields
305 inherits = map(lambda x: (x[0], x[1][2]), self._inherit_fields.items())
306 # complete the field list with the inherited fields which are classic or many2one
307 nfields += filter(lambda x: x[1]._classic_write, inherits)
308 nfields = [x[0] for x in nfields]
310 res = super(cacheable_osv, self).read(cr, user, tofetch, nfields, context, load)
312 self.add((self._name, r['id'], ctx), r)
313 result.append(filter_dict(r, fields))
315 # Appel de fonction si necessaire
321 fvals = self._columns[f].get(cr, self, ids, f, user, context=context)
323 r[f] = fvals[r['id']]
325 # TODO: tri par self._order !!
328 def invalidate(self, key):
329 del self._cache[key[0]][key[1]]
331 def write(self, cr, user, ids, values, context={}):
333 self.invalidate((self._name, id))
334 return super(cacheable_osv, self).write(cr, user, ids, values, context)
336 def unlink(self, cr, user, ids):
338 return super(cacheable_osv, self).unlink(cr, user, ids)
344 #class FakePool(object):
345 # def __init__(self, module):
346 # self.preferred_module = module
348 # def get(self, name):
349 # localpool = module_objects_dict.get(self.preferred_module, {'dict': {}})['dict']
350 # if name in localpool:
351 # obj = localpool[name]
353 # obj = pooler.get_pool(cr.dbname).get(name)
357 # class fake_class(obj.__class__):
358 # def __init__(self):
359 # super(fake_class, self).__init__()
360 # self.pool = fake_pool
362 # return fake_class()