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 except except_osv, inst:
90 self.abortResponse(1, inst.name, inst.exc_type, inst.value)
91 except psycopg.IntegrityError, inst:
92 for key in self._sql_error.keys():
94 self.abortResponse(1, 'Constraint Error', 'warning', self._sql_error[key])
95 self.abortResponse(1, 'Integrity Error', 'warning', inst[0])
98 def execute(self, db, uid, obj, method, *args, **kw):
99 db, pool = pooler.get_db_and_pool(db)
103 res = pool.execute_cr(cr, uid, obj, method, *args, **kw)
112 def exec_workflow_cr(self, cr, uid, obj, method, *args):
113 wf_service = netsvc.LocalService("workflow")
114 wf_service.trg_validate(uid, obj, args[0], method, cr)
117 def exec_workflow(self, db, uid, obj, method, *args):
118 cr = pooler.get_db(db).cursor()
121 res = self.exec_workflow_cr(cr, uid, obj, method, *args)
131 return self.obj_pool.keys()
133 # adds a new object instance to the object pool.
134 # if it already existed, the instance is replaced
135 def add(self, name, obj_inst):
136 if self.obj_pool.has_key(name):
137 del self.obj_pool[name]
138 self.obj_pool[name] = obj_inst
140 module = str(obj_inst.__class__)[6:]
141 module = module[:len(module)-1]
142 module = module.split('.')[0][2:]
143 self.module_object_list.setdefault(module, []).append(obj_inst)
146 obj = self.obj_pool.get(name, None)
147 # We cannot uncomment this line because it breaks initialisation since objects do not initialize
148 # in the correct order and the ORM doesnt support correctly when some objets do not exist yet
149 # assert obj, "object %s does not exist !" % name
152 #TODO: pass a list of modules to load
153 def instanciate(self, module):
154 # print "module list:", module_list
155 # for module in module_list:
157 class_list = module_class_list.get(module, [])
158 # if module not in self.module_object_list:
159 # print "%s class_list:" % module, class_list
160 for klass in class_list:
161 res.append(klass.createInstance(self, module))
164 # print "skipping module", module
166 #pooler.get_pool(cr.dbname) = osv_pool()
169 # See if we can use the pool var instead of the class_pool one
171 class inheritor(type):
172 def __new__(cls, name, bases, d):
173 parent_name = d.get('_inherit', None)
175 parent_class = class_pool.get(parent_name)
176 assert parent_class, "parent class %s does not exist !" % parent_name
177 for s in ('_columns', '_defaults', '_inherits'):
178 new_dict = copy.copy(getattr(parent_class, s))
179 new_dict.update(d.get(s, {}))
181 bases = (parent_class,)
182 res = type.__new__(cls, name, bases, d)
184 # update _inherits of others objects
191 #__metaclass__ = inheritor
194 if not hasattr(cls, '_module'):
195 module = str(cls)[6:]
196 module = module[:len(module)-1]
197 module = module.split('.')[0][2:]
199 module_class_list.setdefault(cls._module, []).append(cls)
200 class_pool[cls._name] = cls
201 if module not in module_list:
202 module_list.append(cls._module)
206 # Goal: try to apply inheritancy at the instanciation level and
207 # put objects in the pool var
209 def createInstance(cls, pool, module):
211 parent_name = hasattr(cls, '_inherit') and cls._inherit
213 parent_class = pool.get(parent_name).__class__
214 assert parent_class, "parent class %s does not exist !" % parent_name
216 for s in ('_columns', '_defaults', '_inherits'):
217 new_dict = copy.copy(getattr(pool.get(parent_name), s))
218 new_dict.update(cls.__dict__.get(s, {}))
220 #bases = (parent_class,)
221 #obj.__class__ += (parent_class,)
222 #res = type.__new__(cls, name, bases, d)
223 name = hasattr(cls,'_name') and cls._name or cls._inherit
225 cls = type(name, (cls, parent_class), ndict)
227 obj = object.__new__(cls)
230 # return object.__new__(cls, pool)
231 createInstance = classmethod(createInstance)
233 def __init__(self, pool):
234 # print "__init__", self._name, pool
235 pool.add(self._name, self)
237 orm.orm.__init__(self)
239 # pooler.get_pool(cr.dbname).add(self._name, self)
240 # print self._name, module
242 class Cacheable(object):
247 def __delete_key(self, key):
249 for key_item in key[:-1]:
250 odico = odico[key_item]
253 def __add_key(self, key, value):
255 for key_item in key[:-1]:
256 odico = odico.setdefault(key_item, {})
257 odico[key[-1]] = value
259 def add(self, key, value):
260 self.__add_key(key, value)
262 def invalidate(self, key):
263 self.__delete_key(key)
276 def filter_dict(d, fields):
278 for f in fields + ['id']:
283 class cacheable_osv(osv, Cacheable):
288 super(cacheable_osv, self).__init__()
290 def read(self, cr, user, ids, fields=[], context={}, load='_classic_read'):
291 fields = fields or self._columns.keys()
292 ctx = [context.get(x, False) for x in self._relevant]
293 result, tofetch = [], []
295 res = self.get(self._name, id, ctx)
299 result.append(filter_dict(res, fields))
301 # gen the list of "local" (ie not inherited) fields which are classic or many2one
302 nfields = filter(lambda x: x[1]._classic_write, self._columns.items())
303 # gen the list of inherited fields
304 inherits = map(lambda x: (x[0], x[1][2]), self._inherit_fields.items())
305 # complete the field list with the inherited fields which are classic or many2one
306 nfields += filter(lambda x: x[1]._classic_write, inherits)
307 nfields = [x[0] for x in nfields]
309 res = super(cacheable_osv, self).read(cr, user, tofetch, nfields, context, load)
311 self.add((self._name, r['id'], ctx), r)
312 result.append(filter_dict(r, fields))
314 # Appel de fonction si necessaire
320 fvals = self._columns[f].get(cr, self, ids, f, user, context=context)
322 r[f] = fvals[r['id']]
324 # TODO: tri par self._order !!
327 def invalidate(self, key):
328 del self._cache[key[0]][key[1]]
330 def write(self, cr, user, ids, values, context={}):
332 self.invalidate((self._name, id))
333 return super(cacheable_osv, self).write(cr, user, ids, values, context)
335 def unlink(self, cr, user, ids):
337 return super(cacheable_osv, self).unlink(cr, user, ids)
343 #class FakePool(object):
344 # def __init__(self, module):
345 # self.preferred_module = module
347 # def get(self, name):
348 # localpool = module_objects_dict.get(self.preferred_module, {'dict': {}})['dict']
349 # if name in localpool:
350 # obj = localpool[name]
352 # obj = pooler.get_pool(cr.dbname).get(name)
356 # class fake_class(obj.__class__):
357 # def __init__(self):
358 # super(fake_class, self).__init__()
359 # self.pool = fake_pool
361 # return fake_class()