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
173 #class inheritor(type):
174 # def __new__(cls, name, bases, d):
175 # parent_name = d.get('_inherit', None)
177 # parent_class = class_pool.get(parent_name)
178 # assert parent_class, "parent class %s does not exist !" % parent_name
179 # for s in ('_columns', '_defaults', '_inherits'):
180 # new_dict = copy.copy(getattr(parent_class, s))
181 # new_dict.update(d.get(s, {}))
183 # bases = (parent_class,)
184 # res = type.__new__(cls, name, bases, d)
186 # # update _inherits of others objects
193 #__metaclass__ = inheritor
196 if not hasattr(cls, '_module'):
197 module = str(cls)[6:]
198 module = module[:len(module)-1]
199 module = module.split('.')[0][2:]
201 module_class_list.setdefault(cls._module, []).append(cls)
202 class_pool[cls._name] = cls
203 if module not in module_list:
204 module_list.append(cls._module)
208 # Goal: try to apply inheritancy at the instanciation level and
209 # put objects in the pool var
211 def createInstance(cls, pool, module):
213 parent_name = hasattr(cls, '_inherit') and cls._inherit
215 parent_class = pool.get(parent_name).__class__
216 assert parent_class, "parent class %s does not exist !" % parent_name
218 for s in ('_columns', '_defaults', '_inherits', '_constraints', '_sql_constraints'):
219 new = copy.copy(getattr(pool.get(parent_name), s))
220 if hasattr(new, 'update'):
221 new.update(cls.__dict__.get(s, {}))
223 new.extend(cls.__dict__.get(s, []))
225 #bases = (parent_class,)
226 #obj.__class__ += (parent_class,)
227 #res = type.__new__(cls, name, bases, d)
228 name = hasattr(cls,'_name') and cls._name or cls._inherit
230 cls = type(name, (cls, parent_class), nattr)
232 obj = object.__new__(cls)
235 # return object.__new__(cls, pool)
236 createInstance = classmethod(createInstance)
238 def __init__(self, pool):
239 # print "__init__", self._name, pool
240 pool.add(self._name, self)
242 orm.orm.__init__(self)
244 # pooler.get_pool(cr.dbname).add(self._name, self)
245 # print self._name, module
247 class Cacheable(object):
252 def __delete_key(self, key):
254 for key_item in key[:-1]:
255 odico = odico[key_item]
258 def __add_key(self, key, value):
260 for key_item in key[:-1]:
261 odico = odico.setdefault(key_item, {})
262 odico[key[-1]] = value
264 def add(self, key, value):
265 self.__add_key(key, value)
267 def invalidate(self, key):
268 self.__delete_key(key)
281 def filter_dict(d, fields):
283 for f in fields + ['id']:
288 class cacheable_osv(osv, Cacheable):
293 super(cacheable_osv, self).__init__()
295 def read(self, cr, user, ids, fields=[], context={}, load='_classic_read'):
296 fields = fields or self._columns.keys()
297 ctx = [context.get(x, False) for x in self._relevant]
298 result, tofetch = [], []
300 res = self.get(self._name, id, ctx)
304 result.append(filter_dict(res, fields))
306 # gen the list of "local" (ie not inherited) fields which are classic or many2one
307 nfields = filter(lambda x: x[1]._classic_write, self._columns.items())
308 # gen the list of inherited fields
309 inherits = map(lambda x: (x[0], x[1][2]), self._inherit_fields.items())
310 # complete the field list with the inherited fields which are classic or many2one
311 nfields += filter(lambda x: x[1]._classic_write, inherits)
312 nfields = [x[0] for x in nfields]
314 res = super(cacheable_osv, self).read(cr, user, tofetch, nfields, context, load)
316 self.add((self._name, r['id'], ctx), r)
317 result.append(filter_dict(r, fields))
319 # Appel de fonction si necessaire
325 fvals = self._columns[f].get(cr, self, ids, f, user, context=context)
327 r[f] = fvals[r['id']]
329 # TODO: tri par self._order !!
332 def invalidate(self, key):
333 del self._cache[key[0]][key[1]]
335 def write(self, cr, user, ids, values, context={}):
337 self.invalidate((self._name, id))
338 return super(cacheable_osv, self).write(cr, user, ids, values, context)
340 def unlink(self, cr, user, ids):
342 return super(cacheable_osv, self).unlink(cr, user, ids)
348 #class FakePool(object):
349 # def __init__(self, module):
350 # self.preferred_module = module
352 # def get(self, name):
353 # localpool = module_objects_dict.get(self.preferred_module, {'dict': {}})['dict']
354 # if name in localpool:
355 # obj = localpool[name]
357 # obj = pooler.get_pool(cr.dbname).get(name)
361 # class fake_class(obj.__class__):
362 # def __init__(self):
363 # super(fake_class, self).__init__()
364 # self.pool = fake_pool
366 # return fake_class()