[FIX] when a module can not be loaded, the pool is delete, allowing to recreate a...
[odoo/odoo.git] / bin / osv / osv.py
1 # -*- encoding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved
6 #    $Id$
7 #
8 #    This program is free software: you can redistribute it and/or modify
9 #    it under the terms of the GNU General Public License as published by
10 #    the Free Software Foundation, either version 3 of the License, or
11 #    (at your option) any later version.
12 #
13 #    This program is distributed in the hope that it will be useful,
14 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
15 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 #    GNU General Public License for more details.
17 #
18 #    You should have received a copy of the GNU General Public License
19 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 #
21 ##############################################################################
22
23 #
24 # OSV: Objects Services
25 #
26
27 import orm
28 import netsvc
29 import pooler
30 import copy
31 import sys
32
33 from psycopg2 import IntegrityError
34 from netsvc import Logger, LOG_ERROR
35 from tools.misc import UpdateableDict
36
37 module_list = []
38 module_class_list = {}
39 class_pool = {}
40
41
42 class except_osv(Exception):
43     def __init__(self, name, value, exc_type='warning'):
44         self.name = name
45         self.exc_type = exc_type
46         self.value = value
47         self.args = (exc_type, name)
48
49
50 from tools.func import wraps
51 class osv_pool(netsvc.Service):
52    
53     def check(f):
54         @wraps(f)
55         def wrapper(self, dbname, *args, **kwargs):
56             try:
57                 if not pooler.get_pool(dbname)._ready:
58                     raise except_osv('Database not ready', 'Currently, this database is not fully loaded and can not be used.')
59                 return f(self, dbname, *args, **kwargs)
60             except orm.except_orm, inst:
61                 self.abortResponse(1, inst.name, 'warning', inst.value)
62             except except_osv, inst:
63                 self.abortResponse(1, inst.name, inst.exc_type, inst.value)
64             except IntegrityError, inst:
65                 for key in self._sql_error.keys():
66                     if key in inst[0]:
67                         self.abortResponse(1, 'Constraint Error', 'warning', self._sql_error[key])
68                 self.abortResponse(1, 'Integrity Error', 'warning', inst[0])
69             except Exception, e:
70                 import traceback
71                 tb_s = reduce(lambda x, y: x+y, traceback.format_exception( sys.exc_type, sys.exc_value, sys.exc_traceback))
72                 logger = Logger()
73                 logger.notifyChannel('web-services', LOG_ERROR, tb_s)
74                 raise
75
76         return wrapper
77
78
79     def __init__(self):
80         self._ready = False
81         self.obj_pool = {}
82         self.module_object_list = {}
83         self.created = []
84         self._sql_error = {}
85         self._store_function = {}
86         self._init = True
87         self._init_parent = {}
88         netsvc.Service.__init__(self, 'object_proxy', audience='')
89         self.joinGroup('web-services')
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_name = hasattr(cls, '_inherit') and cls._inherit
196         if parent_name:
197             raise 'Inherit not supported in osv_memory object !'
198         obj = object.__new__(cls)
199         obj.__init__(pool, cr)
200         return obj
201     createInstance = classmethod(createInstance)
202
203     def __init__(self, pool, cr):
204         pool.add(self._name, self)
205         self.pool = pool
206         orm.orm_memory.__init__(self, cr)
207
208
209
210 class osv(orm.orm):
211     #__metaclass__ = inheritor
212     def __new__(cls):
213         module = str(cls)[6:]
214         module = module[:len(module)-1]
215         module = module.split('.')[0][2:]
216         if not hasattr(cls, '_module'):
217             cls._module = module
218         module_class_list.setdefault(cls._module, []).append(cls)
219         class_pool[cls._name] = cls
220         if module not in module_list:
221             module_list.append(cls._module)
222         return None
223
224     #
225     # Goal: try to apply inheritancy at the instanciation level and
226     #       put objects in the pool var
227     #
228     def createInstance(cls, pool, module, cr):
229         parent_name = hasattr(cls, '_inherit') and cls._inherit
230         if parent_name:
231             parent_class = pool.get(parent_name).__class__
232             assert pool.get(parent_name), "parent class %s does not exist in module %s !" % (parent_name, module)
233             nattr = {}
234             for s in ('_columns', '_defaults', '_inherits', '_constraints', '_sql_constraints'):
235                 new = copy.copy(getattr(pool.get(parent_name), s))
236                 if hasattr(new, 'update'):
237                     new.update(cls.__dict__.get(s, {}))
238                 else:
239                     if s=='_constraints':
240                         for c in cls.__dict__.get(s, []):
241                             exist = False
242                             for c2 in range(len(new)):
243                                 if new[c2][2]==c[2]:
244                                     new[c2] = c
245                                     exist = True
246                                     break
247                             if not exist:
248                                 new.append(c)
249                     else:
250                         new.extend(cls.__dict__.get(s, []))
251                 nattr[s] = new
252             name = hasattr(cls, '_name') and cls._name or cls._inherit
253             cls = type(name, (cls, parent_class), nattr)
254         obj = object.__new__(cls)
255         obj.__init__(pool, cr)
256         return obj
257     createInstance = classmethod(createInstance)
258
259     def __init__(self, pool, cr):
260         pool.add(self._name, self)
261         self.pool = pool
262         orm.orm.__init__(self, cr)
263
264 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
265