KERNEL: remove old inheritor and add _constraints and _sql_constraints to the fields...
[odoo/odoo.git] / bin / osv / osv.py
1 ##############################################################################
2 #
3 # Copyright (c) 2004-2006 TINY SPRL. (http://tiny.be) All Rights Reserved.
4 #                    Fabien Pinckaers <fp@tiny.Be>
5 #
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
11 # Service Company
12 #
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.
17 #
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.
22 #
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.
26 #
27 ##############################################################################
28
29 #
30 # OSV: Objects Services
31 #
32
33 import orm
34 import netsvc
35 import pooler
36 import copy
37
38 import psycopg
39
40 module_list = []
41 module_class_list = {}
42 class_pool = {}
43
44 class except_osv(Exception):
45         def __init__(self, name, value, exc_type='warning'):
46                 self.name = name
47                 self.exc_type = exc_type
48                 self.value = value
49                 self.args = (exc_type,name)
50
51 class osv_pool(netsvc.Service):
52
53         def __init__(self):
54                 self.obj_pool = {}
55                 self.module_object_list = {}
56                 self.created = []
57                 self._sql_error = {}
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)
65
66         def execute_cr(self, cr, uid, obj, method, *args, **kw):
67                 #
68                 # TODO: check security level
69                 #
70                 try:
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():
75                                         if not ty in types:
76                                                 types[ty]=[]
77                                         types[ty].append(id)
78                                         types[obj].remove(id2)
79                                 for t,ids in types.items():
80                                         if len(ids):
81                                                 t = self.obj_pool[t]
82                                                 res = getattr(t,method)(cr, uid, ids, *args[1:], **kw)
83                         else:
84                                 obj = self.obj_pool[obj]
85                                 res = getattr(obj,method)(cr, uid, *args, **kw)
86                         return res
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():
94                                 if key in inst[0]:
95                                         self.abortResponse(1, 'Constraint Error', 'warning', self._sql_error[key])
96                         self.abortResponse(1, 'Integrity Error', 'warning', inst[0])
97
98
99         def execute(self, db, uid, obj, method, *args, **kw):
100                 db, pool = pooler.get_db_and_pool(db)
101                 cr = db.cursor()
102                 try:
103                         try:
104                                 res = pool.execute_cr(cr, uid, obj, method, *args, **kw)
105                                 cr.commit()
106                         except Exception:
107                                 cr.rollback()
108                                 raise
109                 finally:
110                         cr.close()
111                 return res
112
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)
116                 return True
117
118         def exec_workflow(self, db, uid, obj, method, *args):
119                 cr = pooler.get_db(db).cursor()
120                 try:
121                         try:
122                                 res = self.exec_workflow_cr(cr, uid, obj, method, *args)
123                                 cr.commit()
124                         except Exception:
125                                 cr.rollback()
126                                 raise
127                 finally:
128                         cr.close()
129                 return res
130
131         def obj_list(self):
132                 return self.obj_pool.keys()
133
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
140
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)
145
146         def get(self, name):
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
151                 return obj
152
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:
157                 res = []
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))
163                 return res
164 #                       else:
165 #                               print "skipping module", module
166
167 #pooler.get_pool(cr.dbname) = osv_pool()
168
169 #
170 # See if we can use the pool var instead of the class_pool one
171 #
172 # XXX no more used
173 #class inheritor(type):
174 #       def __new__(cls, name, bases, d):
175 #               parent_name = d.get('_inherit', None)
176 #               if parent_name:
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, {}))
182 #                               d[s] = new_dict
183 #                       bases = (parent_class,)
184 #               res = type.__new__(cls, name, bases, d)
185 #               #
186 #               # update _inherits of others objects
187 #               #
188 #               return res
189
190
191
192 class osv(orm.orm):
193         #__metaclass__ = inheritor
194
195         def __new__(cls):
196                 if not hasattr(cls, '_module'):
197                         module = str(cls)[6:]
198                         module = module[:len(module)-1]
199                         module = module.split('.')[0][2:]
200                         cls._module = module
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)
205                 return None
206                 
207         #
208         # Goal: try to apply inheritancy at the instanciation level and
209         #       put objects in the pool var
210         #
211         def createInstance(cls, pool, module):
212 #               obj = cls()
213                 parent_name = hasattr(cls, '_inherit') and cls._inherit
214                 if parent_name:
215                         parent_class = pool.get(parent_name).__class__
216                         assert parent_class, "parent class %s does not exist !" % parent_name
217                         nattr = {}
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, {}))
222                                 else:
223                                         new.extend(cls.__dict__.get(s, []))
224                                 nattr[s] = new
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
229                         #name = str(cls)
230                         cls = type(name, (cls, parent_class), nattr)
231
232                 obj = object.__new__(cls)
233                 obj.__init__(pool)
234                 return obj
235 #               return object.__new__(cls, pool)
236         createInstance = classmethod(createInstance)
237
238         def __init__(self, pool):
239 #               print "__init__", self._name, pool
240                 pool.add(self._name, self)
241                 self.pool = pool
242                 orm.orm.__init__(self)
243                 
244 #               pooler.get_pool(cr.dbname).add(self._name, self)
245 #               print self._name, module
246
247 class Cacheable(object):
248
249         _cache = {}
250         count = 0
251
252         def __delete_key(self, key):
253                 odico = self._cache
254                 for key_item in key[:-1]:
255                         odico = odico[key_item]
256                 del odico[key[-1]]
257         
258         def __add_key(self, key, value):
259                 odico = self._cache
260                 for key_item in key[:-1]:
261                         odico = odico.setdefault(key_item, {})
262                 odico[key[-1]] = value
263
264         def add(self, key, value):
265                 self.__add_key(key, value)
266         
267         def invalidate(self, key):
268                 self.__delete_key(key)
269         
270         def get(self, key):
271                 try:
272                         w = self._cache[key]
273                         return w
274                 except KeyError:
275                         return None
276         
277         def clear(self):
278                 self._cache.clear()
279                 self._items = []
280
281 def filter_dict(d, fields):
282         res = {}
283         for f in fields + ['id']:
284                 if f in d:
285                         res[f] = d[f]
286         return res
287
288 class cacheable_osv(osv, Cacheable):
289
290         _relevant = ['lang']
291
292         def __init__(self):
293                 super(cacheable_osv, self).__init__()
294         
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 = [], []
299                 for id in ids:
300                         res = self.get(self._name, id, ctx)
301                         if not res:
302                                 tofetch.append(id)
303                         else:
304                                 result.append(filter_dict(res, fields))
305
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]
313
314                 res = super(cacheable_osv, self).read(cr, user, tofetch, nfields, context, load)
315                 for r in res:
316                         self.add((self._name, r['id'], ctx), r)
317                         result.append(filter_dict(r, fields))
318
319                 # Appel de fonction si necessaire
320                 tofetch = []
321                 for f in fields:
322                         if f not in nfields:
323                                 tofetch.append(f)
324                 for f in tofetch:
325                         fvals = self._columns[f].get(cr, self, ids, f, user, context=context)
326                         for r in result:
327                                 r[f] = fvals[r['id']]
328
329                 # TODO: tri par self._order !!
330                 return result
331
332         def invalidate(self, key):
333                 del self._cache[key[0]][key[1]]
334         
335         def write(self, cr, user, ids, values, context={}):
336                 for id in ids:
337                         self.invalidate((self._name, id))
338                 return super(cacheable_osv, self).write(cr, user, ids, values, context)
339         
340         def unlink(self, cr, user, ids):
341                 self.clear()
342                 return super(cacheable_osv, self).unlink(cr, user, ids)
343
344 #cacheable_osv = osv
345
346 # vim:noexpandtab:
347
348 #class FakePool(object):
349 #       def __init__(self, module):
350 #               self.preferred_module = module
351         
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]
356 #               else:
357 #                       obj = pooler.get_pool(cr.dbname).get(name)
358 #               return obj
359
360 #               fake_pool = self
361 #               class fake_class(obj.__class__):
362 #                       def __init__(self):
363 #                               super(fake_class, self).__init__()
364 #                               self.pool = fake_pool
365                                 
366 #               return fake_class()
367