[imp] multiple inheritancies
[odoo/odoo.git] / bin / osv / osv.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #    
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
6 #
7 #    This program is free software: you can redistribute it and/or modify
8 #    it under the terms of the GNU Affero General Public License as
9 #    published by the Free Software Foundation, either version 3 of the
10 #    License, or (at your option) any later version.
11 #
12 #    This program is distributed in the hope that it will be useful,
13 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 #    GNU Affero General Public License for more details.
16 #
17 #    You should have received a copy of the GNU Affero General Public License
18 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.     
19 #
20 ##############################################################################
21
22 #
23 # OSV: Objects Services
24 #
25
26 import orm
27 import netsvc
28 import pooler
29 import copy
30 import sys
31
32 from psycopg2 import IntegrityError
33 from netsvc import Logger, LOG_ERROR
34 from tools.misc import UpdateableDict
35
36 from tools.translate import _
37
38 module_list = []
39 module_class_list = {}
40 class_pool = {}
41
42
43 class except_osv(Exception):
44     def __init__(self, name, value, exc_type='warning'):
45         self.name = name
46         self.exc_type = exc_type
47         self.value = value
48         self.args = (exc_type, name)
49
50
51 from tools.func import wraps
52 class osv_pool(netsvc.Service):
53    
54     def check(f):
55         @wraps(f)
56         def wrapper(self, dbname, *args, **kwargs):
57             try:
58                 if not pooler.get_pool(dbname)._ready:
59                     raise except_osv('Database not ready', 'Currently, this database is not fully loaded and can not be used.')
60                 return f(self, dbname, *args, **kwargs)
61             except orm.except_orm, inst:
62                 self.abortResponse(1, inst.name, 'warning', inst.value)
63             except except_osv, inst:
64                 self.abortResponse(1, inst.name, inst.exc_type, inst.value)
65             except IntegrityError, inst:
66                 for key in self._sql_error.keys():
67                     if key in inst[0]:
68                         self.abortResponse(1, _('Constraint Error'), 'warning', _(self._sql_error[key]))
69                 self.abortResponse(1, 'Integrity Error', 'warning', inst[0])
70             except Exception, e:
71                 import traceback, sys
72                 tb_s = "".join(traceback.format_exception(*sys.exc_info()))
73                 logger = Logger()
74                 logger.notifyChannel('web-services', LOG_ERROR, tb_s)
75                 raise
76
77         return wrapper
78
79
80     def __init__(self):
81         self._ready = False
82         self.obj_pool = {}
83         self.module_object_list = {}
84         self.created = []
85         self._sql_error = {}
86         self._store_function = {}
87         self._init = True
88         self._init_parent = {}
89         netsvc.Service.__init__(self, 'object_proxy', audience='')
90         self.exportMethod(self.obj_list)
91         self.exportMethod(self.exec_workflow)
92         self.exportMethod(self.execute)
93
94     def init_set(self, cr, mode):
95         different = mode != self._init
96         if different:
97             if mode:
98                 self._init_parent = {}
99             if not mode:
100                 for o in self._init_parent:
101                     self.get(o)._parent_store_compute(cr)
102             self._init = mode
103         
104         self._ready = True
105         return different
106    
107     def execute_cr(self, cr, uid, obj, method, *args, **kw):
108         object = pooler.get_pool(cr.dbname).get(obj)
109         if not object:
110             raise except_osv('Object Error', 'Object %s doesn\'t exist' % str(obj))
111         return getattr(object, method)(cr, uid, *args, **kw)
112     
113     @check
114     def execute(self, db, uid, obj, method, *args, **kw):
115         db, pool = pooler.get_db_and_pool(db)
116         cr = db.cursor()
117         try:
118             try:
119                 res = pool.execute_cr(cr, uid, obj, method, *args, **kw)
120                 cr.commit()
121             except Exception:
122                 cr.rollback()
123                 raise
124         finally:
125             cr.close()
126         return res
127
128     def exec_workflow_cr(self, cr, uid, obj, method, *args):
129         wf_service = netsvc.LocalService("workflow")
130         return wf_service.trg_validate(uid, obj, args[0], method, cr)
131
132     @check
133     def exec_workflow(self, db, uid, obj, method, *args):
134         cr = pooler.get_db(db).cursor()
135         try:
136             try:
137                 res = self.exec_workflow_cr(cr, uid, obj, method, *args)
138                 cr.commit()
139             except Exception:
140                 cr.rollback()
141                 raise
142         finally:
143             cr.close()
144         return res
145
146     def obj_list(self):
147         return self.obj_pool.keys()
148
149     # adds a new object instance to the object pool.
150     # if it already existed, the instance is replaced
151     def add(self, name, obj_inst):
152         if name in self.obj_pool:
153             del self.obj_pool[name]
154         self.obj_pool[name] = obj_inst
155
156         module = str(obj_inst.__class__)[6:]
157         module = module[:len(module)-1]
158         module = module.split('.')[0][2:]
159         self.module_object_list.setdefault(module, []).append(obj_inst)
160
161     # Return None if object does not exist
162     def get(self, name):
163         obj = self.obj_pool.get(name, None)
164         return obj
165
166     #TODO: pass a list of modules to load
167     def instanciate(self, module, cr):
168         res = []
169         class_list = module_class_list.get(module, [])
170         for klass in class_list:
171             res.append(klass.createInstance(self, module, cr))
172         return res
173
174
175 class osv_memory(orm.orm_memory):
176     #__metaclass__ = inheritor
177     def __new__(cls):
178         module = str(cls)[6:]
179         module = module[:len(module)-1]
180         module = module.split('.')[0][2:]
181         if not hasattr(cls, '_module'):
182             cls._module = module
183         module_class_list.setdefault(cls._module, []).append(cls)
184         class_pool[cls._name] = cls
185         if module not in module_list:
186             module_list.append(cls._module)
187         return None
188
189     #
190     # Goal: try to apply inheritancy at the instanciation level and
191     #       put objects in the pool var
192     #
193     def createInstance(cls, pool, module, cr):
194         name = hasattr(cls, '_name') and cls._name or cls._inherit
195         parent_names = hasattr(cls, '_inherit') and cls._inherit
196         if parent_names:
197             for parent_name in ((type(parent_names)==list) and parent_names or [parent_names]):
198                 parent_class = pool.get(parent_name).__class__
199                 assert pool.get(parent_name), "parent class %s does not exist in module %s !" % (parent_name, module)
200                 nattr = {}
201                 for s in ('_columns', '_defaults'):
202                     new = copy.copy(getattr(pool.get(parent_name), s))
203                     if hasattr(new, 'update'):
204                         new.update(cls.__dict__.get(s, {}))
205                     else:
206                         new.extend(cls.__dict__.get(s, []))
207                     nattr[s] = new
208                 name = hasattr(cls, '_name') and cls._name or cls._inherit
209                 cls = type(name, (cls, parent_class), nattr)
210
211         obj = object.__new__(cls)
212         obj.__init__(pool, cr)
213         return obj
214     createInstance = classmethod(createInstance)
215
216     def __init__(self, pool, cr):
217         pool.add(self._name, self)
218         self.pool = pool
219         orm.orm_memory.__init__(self, cr)
220
221
222
223 class osv(orm.orm):
224     #__metaclass__ = inheritor
225     def __new__(cls):
226         module = str(cls)[6:]
227         module = module[:len(module)-1]
228         module = module.split('.')[0][2:]
229         if not hasattr(cls, '_module'):
230             cls._module = module
231         module_class_list.setdefault(cls._module, []).append(cls)
232         class_pool[cls._name] = cls
233         if module not in module_list:
234             module_list.append(cls._module)
235         return None
236
237     #
238     # Goal: try to apply inheritancy at the instanciation level and
239     #       put objects in the pool var
240     #
241     def createInstance(cls, pool, module, cr):
242         parent_names = hasattr(cls, '_inherit') and cls._inherit
243         if parent_names:
244             for parent_name in ((type(parent_names)==list) and parent_names or [parent_names]):
245                 parent_class = pool.get(parent_name).__class__
246                 assert pool.get(parent_name), "parent class %s does not exist in module %s !" % (parent_name, module)
247                 nattr = {}
248                 for s in ('_columns', '_defaults', '_inherits', '_constraints', '_sql_constraints'):
249                     new = copy.copy(getattr(pool.get(parent_name), s))
250                     if hasattr(new, 'update'):
251                         new.update(cls.__dict__.get(s, {}))
252                     else:
253                         if s=='_constraints':
254                             for c in cls.__dict__.get(s, []):
255                                 exist = False
256                                 for c2 in range(len(new)):
257                                     if new[c2][2]==c[2]:
258                                         new[c2] = c
259                                         exist = True
260                                         break
261                                 if not exist:
262                                     new.append(c)
263                         else:
264                             new.extend(cls.__dict__.get(s, []))
265                     nattr[s] = new
266                 name = hasattr(cls, '_name') and cls._name or cls._inherit
267                 cls = type(name, (cls, parent_class), nattr)
268         obj = object.__new__(cls)
269         obj.__init__(pool, cr)
270         return obj
271     createInstance = classmethod(createInstance)
272
273     def __init__(self, pool, cr):
274         pool.add(self._name, self)
275         self.pool = pool
276         orm.orm.__init__(self, cr)
277
278 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
279