8fb5afae8b182cdc407a2c34807a211ffc5ae5a9
[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 class osv_base(object):
175     def __init__(self, pool, cr):
176         pool.add(self._name, self)
177         self.pool = pool
178         super(osv_base, self).__init__(cr)
179
180     def __new__(cls):
181         module = str(cls)[6:]
182         module = module[:len(module)-1]
183         module = module.split('.')[0][2:]
184         if not hasattr(cls, '_module'):
185             cls._module = module
186         module_class_list.setdefault(cls._module, []).append(cls)
187         class_pool[cls._name] = cls
188         if module not in module_list:
189             module_list.append(cls._module)
190         return None
191
192 class osv_memory(osv_base, orm.orm_memory):
193     #
194     # Goal: try to apply inheritancy at the instanciation level and
195     #       put objects in the pool var
196     #
197     def createInstance(cls, pool, module, cr):
198         name = getattr(cls, '_name', cls._inherit)
199         parent_names = getattr(cls, '_inherit', None)
200         if parent_names:
201             for parent_name in ((type(parent_names)==list) and parent_names or [parent_names]):
202                 parent_class = pool.get(parent_name).__class__
203                 assert pool.get(parent_name), "parent class %s does not exist in module %s !" % (parent_name, module)
204                 nattr = {}
205                 for s in ('_columns', '_defaults'):
206                     new = copy.copy(getattr(pool.get(parent_name), s))
207                     if hasattr(new, 'update'):
208                         new.update(cls.__dict__.get(s, {}))
209                     else:
210                         new.extend(cls.__dict__.get(s, []))
211                     nattr[s] = new
212                 name = getattr(cls, '_name', cls._inherit)
213                 cls = type(name, (cls, parent_class), nattr)
214
215         obj = object.__new__(cls)
216         obj.__init__(pool, cr)
217         return obj
218     createInstance = classmethod(createInstance)
219
220 class osv(osv_base, orm.orm):
221     #
222     # Goal: try to apply inheritancy at the instanciation level and
223     #       put objects in the pool var
224     #
225     def createInstance(cls, pool, module, cr):
226         parent_names = getattr(cls, '_inherit', None)
227         if parent_names:
228             for parent_name in ((type(parent_names)==list) and parent_names or [parent_names]):
229                 parent_class = pool.get(parent_name).__class__
230                 assert pool.get(parent_name), "parent class %s does not exist in module %s !" % (parent_name, module)
231                 nattr = {}
232                 for s in ('_columns', '_defaults', '_inherits', '_constraints', '_sql_constraints'):
233                     new = copy.copy(getattr(pool.get(parent_name), s))
234                     if hasattr(new, 'update'):
235                         new.update(cls.__dict__.get(s, {}))
236                     else:
237                         if s=='_constraints':
238                             for c in cls.__dict__.get(s, []):
239                                 exist = False
240                                 for c2 in range(len(new)):
241                                     if new[c2][2]==c[2]:
242                                         new[c2] = c
243                                         exist = True
244                                         break
245                                 if not exist:
246                                     new.append(c)
247                         else:
248                             new.extend(cls.__dict__.get(s, []))
249                     nattr[s] = new
250                 name = getattr(cls, '_name', cls._inherit)
251                 cls = type(name, (cls, parent_class), nattr)
252         obj = object.__new__(cls)
253         obj.__init__(pool, cr)
254         return obj
255     createInstance = classmethod(createInstance)
256
257 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
258