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):
53
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
cr = pooler.get_db(db).cursor()
102
res = self.execute_cr(cr, uid, obj, method, *args, **kw)
111
def exec_workflow_cr(self, cr, uid, obj, method, *args):
112
wf_service = netsvc.LocalService("workflow")
113
wf_service.trg_validate(uid, obj, args[0], method, cr)
116
def exec_workflow(self, db, uid, obj, method, *args):
117
cr = pooler.get_db(db).cursor()
120
res = self.exec_workflow_cr(cr, uid, obj, method, *args)
130
return self.obj_pool.keys()
132
# adds a new object instance to the object pool.
133
# if it already existed, the instance is replaced
134
def add(self, name, obj_inst):
135
if self.obj_pool.has_key(name):
136
del self.obj_pool[name]
137
self.obj_pool[name] = obj_inst
139
module = str(obj_inst.__class__)[6:]
140
module = module[:len(module)-1]
141
module = module.split('.')[0][2:]
142
self.module_object_list.setdefault(module, []).append(obj_inst)
145
obj = self.obj_pool.get(name, None)
146
# We cannot uncomment this line because it breaks initialisation since objects do not initialize
147
# in the correct order and the ORM doesnt support correctly when some objets do not exist yet
148
# assert obj, "object %s does not exist !" % name
151
#TODO: pass a list of modules to load
152
def instanciate(self, module):
153
# print "module list:", module_list
154
# for module in module_list:
156
class_list = module_class_list.get(module, [])
157
# if module not in self.module_object_list:
158
# print "%s class_list:" % module, class_list
159
for klass in class_list:
160
res.append(klass.createInstance(self, module))
163
# print "skipping module", module
165
#pooler.get_pool(cr.dbname) = osv_pool()
168
# See if we can use the pool var instead of the class_pool one
170
class inheritor(type):
171
def __new__(cls, name, bases, d):
172
parent_name = d.get('_inherit', None)
174
parent_class = class_pool.get(parent_name)
175
assert parent_class, "parent class %s does not exist !" % parent_name
176
for s in ('_columns', '_defaults', '_inherits'):
177
new_dict = copy.copy(getattr(parent_class, s))
178
new_dict.update(d.get(s, {}))
180
bases = (parent_class,)
181
res = type.__new__(cls, name, bases, d)
183
# update _inherits of others objects
190
#__metaclass__ = inheritor
193
if not hasattr(cls, '_module'):
194
module = str(cls)[6:]
195
module = module[:len(module)-1]
196
module = module.split('.')[0][2:]
198
module_class_list.setdefault(cls._module, []).append(cls)
199
class_pool[cls._name] = cls
200
if module not in module_list:
201
module_list.append(cls._module)
205
# Goal: try to apply inheritancy at the instanciation level and
206
# put objects in the pool var
208
def createInstance(cls, pool, module):
210
parent_name = hasattr(cls, '_inherit') and cls._inherit
212
parent_class = pool.get(parent_name).__class__
213
assert parent_class, "parent class %s does not exist !" % parent_name
215
for s in ('_columns', '_defaults', '_inherits'):
216
new_dict = copy.copy(getattr(pool.get(parent_name), s))
217
new_dict.update(cls.__dict__.get(s, {}))
219
#bases = (parent_class,)
220
#obj.__class__ += (parent_class,)
221
#res = type.__new__(cls, name, bases, d)
222
name = hasattr(cls,'_name') and cls._name or cls._inherit
224
cls = type(name, (cls, parent_class), ndict)
226
obj = object.__new__(cls)
229
# return object.__new__(cls, pool)
230
createInstance = classmethod(createInstance)
232
def __init__(self, pool):
233
# print "__init__", self._name, pool
234
pool.add(self._name, self)
236
orm.orm.__init__(self)
238
# pooler.get_pool(cr.dbname).add(self._name, self)
239
# print self._name, module
241
class Cacheable(object):
246
def __delete_key(self, key):
248
for key_item in key[:-1]:
249
odico = odico[key_item]
252
def __add_key(self, key, value):
254
for key_item in key[:-1]:
255
odico = odico.setdefault(key_item, {})
256
odico[key[-1]] = value
258
def add(self, key, value):
259
self.__add_key(key, value)
261
def invalidate(self, key):
262
self.__delete_key(key)
275
def filter_dict(d, fields):
277
for f in fields + ['id']:
282
class cacheable_osv(osv, Cacheable):
287
super(cacheable_osv, self).__init__()
289
def read(self, cr, user, ids, fields=[], context={}, load='_classic_read'):
290
fields = fields or self._columns.keys()
291
ctx = [context.get(x, False) for x in self._relevant]
292
result, tofetch = [], []
294
res = self.get(self._name, id, ctx)
298
result.append(filter_dict(res, fields))
300
# gen the list of "local" (ie not inherited) fields which are classic or many2one
301
nfields = filter(lambda x: x[1]._classic_write, self._columns.items())
302
# gen the list of inherited fields
303
inherits = map(lambda x: (x[0], x[1][2]), self._inherit_fields.items())
304
# complete the field list with the inherited fields which are classic or many2one
305
nfields += filter(lambda x: x[1]._classic_write, inherits)
306
nfields = [x[0] for x in nfields]
308
res = super(cacheable_osv, self).read(cr, user, tofetch, nfields, context, load)
310
self.add((self._name, r['id'], ctx), r)
311
result.append(filter_dict(r, fields))
313
# Appel de fonction si necessaire
319
fvals = self._columns[f].get(cr, self, ids, f, user, context=context)
321
r[f] = fvals[r['id']]
323
# TODO: tri par self._order !!
326
def invalidate(self, key):
327
del self._cache[key[0]][key[1]]
329
def write(self, cr, user, ids, values, context={}):
331
self.invalidate((self._name, id))
332
return super(cacheable_osv, self).write(cr, user, ids, values, context)
334
def unlink(self, cr, user, ids):
336
return super(cacheable_osv, self).unlink(cr, user, ids)
342
#class FakePool(object):
343
# def __init__(self, module):
344
# self.preferred_module = module
346
# def get(self, name):
347
# localpool = module_objects_dict.get(self.preferred_module, {'dict': {}})['dict']
348
# if name in localpool:
349
# obj = localpool[name]
351
# obj = pooler.get_pool(cr.dbname).get(name)
355
# class fake_class(obj.__class__):
356
# def __init__(self):
357
# super(fake_class, self).__init__()
358
# self.pool = fake_pool
360
# return fake_class()