speed_improve
[odoo/odoo.git] / bin / osv / fields.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 # . Fields:
23 #      - simple
24 #      - relations (one2many, many2one, many2many)
25 #      - function
26 #
27 # Fields Attributes:
28 #   _classic_read: is a classic sql fields
29 #   _type   : field type
30 #   readonly
31 #   required
32 #   size
33 #
34 from collections import defaultdict
35 import string
36 import netsvc
37 import sys
38
39 from psycopg2 import Binary
40 import warnings
41
42 import tools
43 from tools.translate import _
44
45 def _symbol_set(symb):
46     if symb == None or symb == False:
47         return None
48     elif isinstance(symb, unicode):
49         return symb.encode('utf-8')
50     return str(symb)
51
52
53 class _column(object):
54     _classic_read = True
55     _classic_write = True
56     _prefetch = True
57     _properties = False
58     _type = 'unknown'
59     _obj = None
60     _multi = False
61     _symbol_c = '%s'
62     _symbol_f = _symbol_set
63     _symbol_set = (_symbol_c, _symbol_f)
64     _symbol_get = None
65
66     def __init__(self, string='unknown', required=False, readonly=False, domain=None, context={}, states=None, priority=0, change_default=False, size=None, ondelete="set null", translate=False, select=False, **args):
67         self.states = states or {}
68         self.string = string
69         self.readonly = readonly
70         self.required = required
71         self.size = size
72         self.help = args.get('help', '')
73         self.priority = priority
74         self.change_default = change_default
75         self.ondelete = ondelete
76         self.translate = translate
77         self._domain = domain or []
78         self._context = context
79         self.write = False
80         self.read = False
81         self.view_load = 0
82         self.select = select
83         self.selectable = True
84         self.group_operator = args.get('group_operator', False)
85         for a in args:
86             if args[a]:
87                 setattr(self, a, args[a])
88
89     def restart(self):
90         pass
91
92     def set(self, cr, obj, id, name, value, user=None, context=None):
93         cr.execute('update '+obj._table+' set '+name+'='+self._symbol_set[0]+' where id=%s', (self._symbol_set[1](value), id))
94
95     def set_memory(self, cr, obj, id, name, value, user=None, context=None):
96         raise Exception(_('Not implemented set_memory method !'))
97
98     def get_memory(self, cr, obj, ids, name, user=None, context=None, values=None):
99         raise Exception(_('Not implemented get_memory method !'))
100
101     def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
102         raise Exception(_('undefined get method !'))
103
104     def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, context=None):
105         ids = obj.search(cr, uid, args+self._domain+[(name, 'ilike', value)], offset, limit, context=context)
106         res = obj.read(cr, uid, ids, [name], context=context)
107         return [x[name] for x in res]
108
109     def search_memory(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, context=None):
110         raise Exception(_('Not implemented search_memory method !'))
111
112
113 # ---------------------------------------------------------
114 # Simple fields
115 # ---------------------------------------------------------
116 class boolean(_column):
117     _type = 'boolean'
118     _symbol_c = '%s'
119     _symbol_f = lambda x: x and 'True' or 'False'
120     _symbol_set = (_symbol_c, _symbol_f)
121
122 class integer_big(_column):
123     _type = 'integer_big'
124     _symbol_c = '%s'
125     _symbol_f = lambda x: int(x or 0)
126     _symbol_set = (_symbol_c, _symbol_f)
127     _symbol_get = lambda self,x: x or 0
128
129 class integer(_column):
130     _type = 'integer'
131     _symbol_c = '%s'
132     _symbol_f = lambda x: int(x or 0)
133     _symbol_set = (_symbol_c, _symbol_f)
134     _symbol_get = lambda self,x: x or 0
135
136
137 class reference(_column):
138     _type = 'reference'
139     def __init__(self, string, selection, size, **args):
140         _column.__init__(self, string=string, size=size, selection=selection, **args)
141
142
143 class char(_column):
144     _type = 'char'
145
146     def __init__(self, string, size, **args):
147         _column.__init__(self, string=string, size=size, **args)
148         self._symbol_set = (self._symbol_c, self._symbol_set_char)
149
150     # takes a string (encoded in utf8) and returns a string (encoded in utf8)
151     def _symbol_set_char(self, symb):
152         #TODO:
153         # * we need to remove the "symb==False" from the next line BUT
154         #   for now too many things rely on this broken behavior
155         # * the symb==None test should be common to all data types
156         if symb == None or symb == False:
157             return None
158
159         # we need to convert the string to a unicode object to be able
160         # to evaluate its length (and possibly truncate it) reliably
161         u_symb = tools.ustr(symb)
162
163         return u_symb[:self.size].encode('utf8')
164
165
166 class text(_column):
167     _type = 'text'
168
169 import __builtin__
170
171 class float(_column):
172     _type = 'float'
173     _symbol_c = '%s'
174     _symbol_f = lambda x: __builtin__.float(x or 0.0)
175     _symbol_set = (_symbol_c, _symbol_f)
176     _symbol_get = lambda self,x: x or 0.0
177
178     def __init__(self, string='unknown', digits=None, digits_compute=None, **args):
179         _column.__init__(self, string=string, **args)
180         self.digits = digits
181         self.digits_compute = digits_compute
182
183
184     def digits_change(self, cr):
185         if self.digits_compute:
186             t = self.digits_compute(cr)
187             self._symbol_set=('%s', lambda x: ('%.'+str(t[1])+'f') % (__builtin__.float(x or 0.0),))
188             self.digits = t
189
190 class date(_column):
191     _type = 'date'
192
193
194 class datetime(_column):
195     _type = 'datetime'
196
197
198 class time(_column):
199     _type = 'time'
200
201 class binary(_column):
202     _type = 'binary'
203     _symbol_c = '%s'
204     _symbol_f = lambda symb: symb and Binary(symb) or None
205     _symbol_set = (_symbol_c, _symbol_f)
206     _symbol_get = lambda self, x: x and str(x)
207
208     _classic_read = False
209     _prefetch = False
210
211     def __init__(self, string='unknown', filters=None, **args):
212         _column.__init__(self, string=string, **args)
213         self.filters = filters
214
215     def get_memory(self, cr, obj, ids, name, user=None, context=None, values=None):
216         if not context:
217             context = {}
218         if not values:
219             values = []
220         res = {}
221         for i in ids:
222             val = None
223             for v in values:
224                 if v['id'] == i:
225                     val = v[name]
226                     break
227             if context.get('bin_size', False) and val:
228                 res[i] = tools.human_size(long(val))
229             else:
230                 res[i] = val
231         return res
232
233     get = get_memory
234
235
236 class selection(_column):
237     _type = 'selection'
238
239     def __init__(self, selection, string='unknown', **args):
240         _column.__init__(self, string=string, **args)
241         self.selection = selection
242
243 # ---------------------------------------------------------
244 # Relationals fields
245 # ---------------------------------------------------------
246
247 #
248 # Values: (0, 0,  { fields })    create
249 #         (1, ID, { fields })    update
250 #         (2, ID)                remove (delete)
251 #         (3, ID)                unlink one (target id or target of relation)
252 #         (4, ID)                link
253 #         (5)                    unlink all (only valid for one2many)
254 #
255 #CHECKME: dans la pratique c'est quoi la syntaxe utilisee pour le 5? (5) ou (5, 0)?
256 class one2one(_column):
257     _classic_read = False
258     _classic_write = True
259     _type = 'one2one'
260
261     def __init__(self, obj, string='unknown', **args):
262         warnings.warn("The one2one field doesn't work anymore", DeprecationWarning)
263         _column.__init__(self, string=string, **args)
264         self._obj = obj
265
266     def set(self, cr, obj_src, id, field, act, user=None, context=None):
267         if not context:
268             context = {}
269         obj = obj_src.pool.get(self._obj)
270         self._table = obj_src.pool.get(self._obj)._table
271         if act[0] == 0:
272             id_new = obj.create(cr, user, act[1])
273             cr.execute('update '+obj_src._table+' set '+field+'=%s where id=%s', (id_new, id))
274         else:
275             cr.execute('select '+field+' from '+obj_src._table+' where id=%s', (act[0],))
276             id = cr.fetchone()[0]
277             obj.write(cr, user, [id], act[1], context=context)
278
279     def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, context=None):
280         return obj.pool.get(self._obj).search(cr, uid, args+self._domain+[('name', 'like', value)], offset, limit, context=context)
281
282
283 class many2one(_column):
284     _classic_read = False
285     _classic_write = True
286     _type = 'many2one'
287     _symbol_c = '%s'
288     _symbol_f = lambda x: x or None
289     _symbol_set = (_symbol_c, _symbol_f)
290
291     def __init__(self, obj, string='unknown', **args):
292         _column.__init__(self, string=string, **args)
293         self._obj = obj
294
295     def set_memory(self, cr, obj, id, field, values, user=None, context=None):
296         obj.datas.setdefault(id, {})
297         obj.datas[id][field] = values
298
299     def get_memory(self, cr, obj, ids, name, user=None, context=None, values=None):
300         result = {}
301         for id in ids:
302             result[id] = obj.datas[id].get(name, False)
303         return result
304
305     def get(self, cr, obj, ids, name, user=None, context=None, values=None):
306         context = context or {}
307         values = values or {}
308
309         res = {}
310         for r in values:
311             res[r['id']] = r[name]
312         for id in ids:
313             res.setdefault(id, '')
314         obj = obj.pool.get(self._obj)
315
316         # build a dictionary of the form {'id_of_distant_resource': name_of_distant_resource}
317         # uid=1 because visibility of a many2one= visibility of parent object
318         records = dict(obj.name_get(cr, 1, list(set(filter(None, res.values()))), context=context))
319         for id in res:
320             if id in records:
321                 res[id] = (id, records[id])
322             else:
323                 res[id] = False
324         return res
325
326     def set(self, cr, obj_src, id, field, values, user=None, context=None):
327         if not context:
328             context = {}
329         obj = obj_src.pool.get(self._obj)
330         self._table = obj_src.pool.get(self._obj)._table
331         if type(values) == type([]):
332             for act in values:
333                 if act[0] == 0:
334                     id_new = obj.create(cr, act[2])
335                     cr.execute('update '+obj_src._table+' set '+field+'=%s where id=%s', (id_new, id))
336                 elif act[0] == 1:
337                     obj.write(cr, [act[1]], act[2], context=context)
338                 elif act[0] == 2:
339                     cr.execute('delete from '+self._table+' where id=%s', (act[1],))
340                 elif act[0] == 3 or act[0] == 5:
341                     cr.execute('update '+obj_src._table+' set '+field+'=null where id=%s', (id,))
342                 elif act[0] == 4:
343                     cr.execute('update '+obj_src._table+' set '+field+'=%s where id=%s', (act[1], id))
344         else:
345             if values:
346                 cr.execute('update '+obj_src._table+' set '+field+'=%s where id=%s', (values, id))
347             else:
348                 cr.execute('update '+obj_src._table+' set '+field+'=null where id=%s', (id,))
349
350     def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, context=None):
351         return obj.pool.get(self._obj).search(cr, uid, args+self._domain+[('name', 'like', value)], offset, limit, context=context)
352
353
354 class one2many(_column):
355     _classic_read = False
356     _classic_write = False
357     _prefetch = False
358     _type = 'one2many'
359
360     def __init__(self, obj, fields_id, string='unknown', limit=None, **args):
361         _column.__init__(self, string=string, **args)
362         self._obj = obj
363         self._fields_id = fields_id
364         self._limit = limit
365         #one2many can't be used as condition for defaults
366         assert(self.change_default != True)
367
368     def get_memory(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
369         if not context:
370             context = {}
371         if self._context:
372             context = context.copy()
373             context.update(self._context)
374         if not values:
375             values = {}
376         res = {}
377         for id in ids:
378             res[id] = []
379         ids2 = obj.pool.get(self._obj).search(cr, user, [(self._fields_id, 'in', ids)], limit=self._limit, context=context)
380         for r in obj.pool.get(self._obj).read(cr, user, ids2, [self._fields_id], context=context, load='_classic_write'):
381             if r[self._fields_id] in res:
382                 res[r[self._fields_id]].append(r['id'])
383         return res
384
385     def set_memory(self, cr, obj, id, field, values, user=None, context=None):
386         if not context:
387             context = {}
388         if self._context:
389             context = context.copy()
390         context.update(self._context)
391         if not values:
392             return
393         obj = obj.pool.get(self._obj)
394         for act in values:
395             if act[0] == 0:
396                 act[2][self._fields_id] = id
397                 obj.create(cr, user, act[2], context=context)
398             elif act[0] == 1:
399                 obj.write(cr, user, [act[1]], act[2], context=context)
400             elif act[0] == 2:
401                 obj.unlink(cr, user, [act[1]], context=context)
402             elif act[0] == 3:
403                 obj.datas[act[1]][self._fields_id] = False
404             elif act[0] == 4:
405                 obj.datas[act[1]] = id
406             elif act[0] == 5:
407                 for o in obj.datas.values():
408                     if o[self._fields_id] == id:
409                         o[self._fields_id] = False
410             elif act[0] == 6:
411                 for id2 in (act[2] or []):
412                     obj.datas[id2][self._fields_id] = id
413
414     def search_memory(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, operator='like', context=None):
415         raise _('Not Implemented')
416
417     def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
418         if not context:
419             context = {}
420         if self._context:
421             context = context.copy()
422         context.update(self._context)
423         if not values:
424             values = {}
425
426         res = defaultdict(list)
427
428         ids2 = obj.pool.get(self._obj).search(cr, user, self._domain + [(self._fields_id, 'in', ids)], limit=self._limit, context=context)
429         for r in obj.pool.get(self._obj)._read_flat(cr, user, ids2, [self._fields_id], context=context, load='_classic_write'):
430             res[r[self._fields_id]].append(r['id'])
431         return res
432
433     def set(self, cr, obj, id, field, values, user=None, context=None):
434         result = []
435         if not context:
436             context = {}
437         if self._context:
438             context = context.copy()
439         context.update(self._context)
440         context['no_store_function'] = True
441         if not values:
442             return
443         _table = obj.pool.get(self._obj)._table
444         obj = obj.pool.get(self._obj)
445         for act in values:
446             if act[0] == 0:
447                 act[2][self._fields_id] = id
448                 id_new = obj.create(cr, user, act[2], context=context)
449                 result += obj._store_get_values(cr, user, [id_new], act[2].keys(), context)
450             elif act[0] == 1:
451                 obj.write(cr, user, [act[1]], act[2], context=context)
452             elif act[0] == 2:
453                 obj.unlink(cr, user, [act[1]], context=context)
454             elif act[0] == 3:
455                 cr.execute('update '+_table+' set '+self._fields_id+'=null where id=%s', (act[1],))
456             elif act[0] == 4:
457                 cr.execute('update '+_table+' set '+self._fields_id+'=%s where id=%s', (id, act[1]))
458             elif act[0] == 5:
459                 cr.execute('update '+_table+' set '+self._fields_id+'=null where '+self._fields_id+'=%s', (id,))
460             elif act[0] == 6:
461                 obj.write(cr, user, act[2], {self._fields_id:id}, context=context or {})
462                 ids2 = act[2] or [0]
463                 cr.execute('select id from '+_table+' where '+self._fields_id+'=%s and id <> ALL (%s)', (id,ids2))
464                 ids3 = map(lambda x:x[0], cr.fetchall())
465                 obj.write(cr, user, ids3, {self._fields_id:False}, context=context or {})
466         return result
467
468     def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, operator='like', context=None):
469         return obj.pool.get(self._obj).name_search(cr, uid, value, self._domain, operator, context=context,limit=limit)
470
471
472 #
473 # Values: (0, 0,  { fields })    create
474 #         (1, ID, { fields })    update (write fields to ID)
475 #         (2, ID)                remove (calls unlink on ID, that will also delete the relationship because of the ondelete)
476 #         (3, ID)                unlink (delete the relationship between the two objects but does not delete ID)
477 #         (4, ID)                link (add a relationship)
478 #         (5, ID)                unlink all
479 #         (6, ?, ids)            set a list of links
480 #
481 class many2many(_column):
482     _classic_read = False
483     _classic_write = False
484     _prefetch = False
485     _type = 'many2many'
486     def __init__(self, obj, rel, id1, id2, string='unknown', limit=None, **args):
487         _column.__init__(self, string=string, **args)
488         self._obj = obj
489         if '.' in rel:
490             raise Exception(_('The second argument of the many2many field %s must be a SQL table !'\
491                 'You used %s, which is not a valid SQL table name.')% (string,rel))
492         self._rel = rel
493         self._id1 = id1
494         self._id2 = id2
495         self._limit = limit
496
497     def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
498         if not context:
499             context = {}
500         if not values:
501             values = {}
502         res = {}
503         if not ids:
504             return res
505         for id in ids:
506             res[id] = []
507         limit_str = self._limit is not None and ' limit %d' % self._limit or ''
508         obj = obj.pool.get(self._obj)
509
510         d1, d2, tables = obj.pool.get('ir.rule').domain_get(cr, user, obj._name, context=context)
511         if d1:
512             d1 = ' and ' + ' and '.join(d1)
513         else: d1 = ''
514         query = 'SELECT %(rel)s.%(id2)s, %(rel)s.%(id1)s \
515                    FROM %(rel)s, %(tbl)s \
516                   WHERE %(rel)s.%(id1)s in %%s \
517                     AND %(rel)s.%(id2)s = %(tbl)s.id \
518                  %(d1)s  \
519                  %(limit)s \
520                   ORDER BY %(tbl)s.%(order)s \
521                  OFFSET %(offset)d' \
522             % {'rel': self._rel,
523                'tbl': obj._table,
524                'id1': self._id1,
525                'id2': self._id2,
526                'd1': d1,
527                'limit': limit_str,
528                'order': obj._order,
529                'offset': offset,
530               }
531         cr.execute(query, [tuple(ids)] + d2)
532         for r in cr.fetchall():
533             res[r[1]].append(r[0])
534         return res
535
536     def set(self, cr, obj, id, name, values, user=None, context=None):
537         if not context:
538             context = {}
539         if not values:
540             return
541         obj = obj.pool.get(self._obj)
542         for act in values:
543             if not (isinstance(act, list) or isinstance(act, tuple)) or not act:
544                 continue
545             if act[0] == 0:
546                 idnew = obj.create(cr, user, act[2])
547                 cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%s,%s)', (id, idnew))
548             elif act[0] == 1:
549                 obj.write(cr, user, [act[1]], act[2], context=context)
550             elif act[0] == 2:
551                 obj.unlink(cr, user, [act[1]], context=context)
552             elif act[0] == 3:
553                 cr.execute('delete from '+self._rel+' where ' + self._id1 + '=%s and '+ self._id2 + '=%s', (id, act[1]))
554             elif act[0] == 4:
555                 cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%s,%s)', (id, act[1]))
556             elif act[0] == 5:
557                 cr.execute('update '+self._rel+' set '+self._id2+'=null where '+self._id2+'=%s', (id,))
558             elif act[0] == 6:
559
560                 d1, d2,tables = obj.pool.get('ir.rule').domain_get(cr, user, obj._name, context=context)
561                 if d1:
562                     d1 = ' and ' + ' and '.join(d1)
563                 else:
564                     d1 = ''
565                 cr.execute('delete from '+self._rel+' where '+self._id1+'=%s AND '+self._id2+' IN (SELECT '+self._rel+'.'+self._id2+' FROM '+self._rel+', '+','.join(tables)+' WHERE '+self._rel+'.'+self._id1+'=%s AND '+self._rel+'.'+self._id2+' = '+obj._table+'.id '+ d1 +')', [id, id]+d2)
566
567                 for act_nbr in act[2]:
568                     cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%s, %s)', (id, act_nbr))
569
570     #
571     # TODO: use a name_search
572     #
573     def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, operator='like', context=None):
574         return obj.pool.get(self._obj).search(cr, uid, args+self._domain+[('name', operator, value)], offset, limit, context=context)
575
576     def get_memory(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
577         result = {}
578         for id in ids:
579             result[id] = obj.datas[id].get(name, [])
580         return result
581
582     def set_memory(self, cr, obj, id, name, values, user=None, context=None):
583         if not values:
584             return
585         for act in values:
586             # TODO: use constants instead of these magic numbers
587             if act[0] == 0:
588                 raise _('Not Implemented')
589             elif act[0] == 1:
590                 raise _('Not Implemented')
591             elif act[0] == 2:
592                 raise _('Not Implemented')
593             elif act[0] == 3:
594                 raise _('Not Implemented')
595             elif act[0] == 4:
596                 raise _('Not Implemented')
597             elif act[0] == 5:
598                 raise _('Not Implemented')
599             elif act[0] == 6:
600                 obj.datas[id][name] = act[2]
601
602
603 def get_nice_size(a):
604     (x,y) = a
605     if isinstance(y, (int,long)):
606         size = y
607     elif y:
608         size = len(y)
609     else:
610         size = 0
611     return (x, tools.human_size(size))
612
613 # ---------------------------------------------------------
614 # Function fields
615 # ---------------------------------------------------------
616 class function(_column):
617     _classic_read = False
618     _classic_write = False
619     _prefetch = False
620     _type = 'function'
621     _properties = True
622
623 #
624 # multi: compute several fields in one call
625 #
626     def __init__(self, fnct, arg=None, fnct_inv=None, fnct_inv_arg=None, type='float', fnct_search=None, obj=None, method=False, store=False, multi=False, **args):
627         _column.__init__(self, **args)
628         self._obj = obj
629         self._method = method
630         self._fnct = fnct
631         self._fnct_inv = fnct_inv
632         self._arg = arg
633         self._multi = multi
634         if 'relation' in args:
635             self._obj = args['relation']
636
637         self.digits = args.get('digits', (16,2))
638         self.digits_compute = args.get('digits_compute', None)
639
640         self._fnct_inv_arg = fnct_inv_arg
641         if not fnct_inv:
642             self.readonly = 1
643         self._type = type
644         self._fnct_search = fnct_search
645         self.store = store
646
647         if not fnct_search and not store:
648             self.selectable = False
649
650         if store:
651             if self._type != 'many2one':
652                 # m2o fields need to return tuples with name_get, not just foreign keys
653                 self._classic_read = True
654             self._classic_write = True
655             if type=='binary':
656                 self._symbol_get=lambda x:x and str(x)
657
658         if type == 'float':
659             self._symbol_c = float._symbol_c
660             self._symbol_f = float._symbol_f
661             self._symbol_set = float._symbol_set
662
663         if type == 'boolean':
664             self._symbol_c = boolean._symbol_c
665             self._symbol_f = boolean._symbol_f
666             self._symbol_set = boolean._symbol_set
667
668     def digits_change(self, cr):
669         if self.digits_compute:
670             t = self.digits_compute(cr)
671             self._symbol_set=('%s', lambda x: ('%.'+str(t[1])+'f') % (__builtin__.float(x or 0.0),))
672             self.digits = t
673
674
675     def search(self, cr, uid, obj, name, args, context=None):
676         if not self._fnct_search:
677             #CHECKME: should raise an exception
678             return []
679         return self._fnct_search(obj, cr, uid, obj, name, args, context=context)
680
681     def get(self, cr, obj, ids, name, user=None, context=None, values=None):
682         if not context:
683             context = {}
684         if not values:
685             values = {}
686         res = {}
687         if self._method:
688             res = self._fnct(obj, cr, user, ids, name, self._arg, context)
689         else:
690             res = self._fnct(cr, obj._table, ids, name, self._arg, context)
691
692         if self._type == "many2one" :
693             # Filtering only integer/long values if passed
694             res_ids = [x for x in res.values() if x and isinstance(x, (int,long))]
695
696             if res_ids:
697                 obj_model = obj.pool.get(self._obj)
698                 dict_names = dict(obj_model.name_get(cr, user, res_ids, context))
699                 for r in res.keys():
700                     if res[r] and res[r] in dict_names:
701                         res[r] = (res[r], dict_names[res[r]])
702
703         if self._type == 'binary' and context.get('bin_size', False):
704             # convert the data returned by the function with the size of that data...
705             res = dict(map( get_nice_size, res.items()))
706         if self._type == "integer":
707             for r in res.keys():
708                 # Converting value into string so that it does not affect XML-RPC Limits
709                 if isinstance(res[r],dict): # To treat integer values with _multi attribute
710                     for record in res[r].keys():
711                         res[r][record] = str(res[r][record])
712                 else:
713                     res[r] = str(res[r])
714         return res
715     get_memory = get
716
717     def set(self, cr, obj, id, name, value, user=None, context=None):
718         if not context:
719             context = {}
720         if self._fnct_inv:
721             self._fnct_inv(obj, cr, user, id, name, value, self._fnct_inv_arg, context)
722     set_memory = set
723
724 # ---------------------------------------------------------
725 # Related fields
726 # ---------------------------------------------------------
727
728 class related(function):
729
730     def _fnct_search(self, tobj, cr, uid, obj=None, name=None, domain=None, context={}):
731         self._field_get2(cr, uid, obj, context)
732         i = len(self._arg)-1
733         sarg = name
734         while i>0:
735             if type(sarg) in [type([]), type( (1,) )]:
736                 where = [(self._arg[i], 'in', sarg)]
737             else:
738                 where = [(self._arg[i], '=', sarg)]
739             if domain:
740                 where = map(lambda x: (self._arg[i],x[1], x[2]), domain)
741                 domain = []
742             sarg = obj.pool.get(self._relations[i]['object']).search(cr, uid, where, context=context)
743             i -= 1
744         return [(self._arg[0], 'in', sarg)]
745
746     def _fnct_write(self,obj,cr, uid, ids, field_name, values, args, context=None):
747         self._field_get2(cr, uid, obj, context)
748         if type(ids) != type([]):
749             ids=[ids]
750         objlst = obj.browse(cr, uid, ids)
751         for data in objlst:
752             t_id = data.id
753             t_data = data
754             for i in range(len(self.arg)):
755                 if not t_data: break
756                 field_detail = self._relations[i]
757                 if not t_data[self.arg[i]]:
758                     if self._type not in ('one2many', 'many2many'):
759                         t_id = t_data['id']
760                     t_data = False
761                 elif field_detail['type'] in ('one2many', 'many2many'):
762                     if self._type != "many2one":
763                         t_id = t_data.id
764                         t_data = t_data[self.arg[i]][0]
765                     else:
766                         t_data = False
767                 else:
768                     t_id = t_data['id']
769                     t_data = t_data[self.arg[i]]
770             else:
771                 model = obj.pool.get(self._relations[-1]['object'])
772                 model.write(cr, uid, [t_id], {args[-1]: values}, context=context)
773
774     def _fnct_read(self, obj, cr, uid, ids, field_name, args, context=None):
775         self._field_get2(cr, uid, obj, context)
776         if not ids: return {}
777         relation = obj._name
778         if self._type in ('one2many', 'many2many'):
779             res = {}.fromkeys(ids, [])
780         else:
781             res = {}.fromkeys(ids, False)
782
783         objlst = obj.browse(cr, 1, ids, context=context)
784         for data in objlst:
785             if not data:
786                 continue
787             t_data = data
788             relation = obj._name
789             for i in range(len(self.arg)):
790                 field_detail = self._relations[i]
791                 relation = field_detail['object']
792                 try:
793                     if not t_data[self.arg[i]]:
794                         t_data = False
795                         break
796                 except:
797                     t_data = False
798                     break
799                 if field_detail['type'] in ('one2many', 'many2many') and i != len(self.arg) - 1:
800                     t_data = t_data[self.arg[i]][0]
801                 elif t_data:
802                     t_data = t_data[self.arg[i]]
803             if type(t_data) == type(objlst[0]):
804                 res[data.id] = t_data.id
805             elif t_data:
806                 res[data.id] = t_data
807         if self._type=='many2one':
808             ids = filter(None, res.values())
809             if ids:
810                 ng = dict(obj.pool.get(self._obj).name_get(cr, 1, ids, context=context))
811                 for r in res:
812                     if res[r]:
813                         res[r] = (res[r], ng[res[r]])
814         elif self._type in ('one2many', 'many2many'):
815             for r in res:
816                 if res[r]:
817                     res[r] = [x.id for x in res[r]]
818         return res
819
820     def __init__(self, *arg, **args):
821         self.arg = arg
822         self._relations = []
823         super(related, self).__init__(self._fnct_read, arg, self._fnct_write, fnct_inv_arg=arg, method=True, fnct_search=self._fnct_search, **args)
824         if self.store is True:
825             # TODO: improve here to change self.store = {...} according to related objects
826             pass
827
828     def _field_get2(self, cr, uid, obj, context={}):
829         if self._relations:
830             return
831         obj_name = obj._name
832         for i in range(len(self._arg)):
833             f = obj.pool.get(obj_name).fields_get(cr, uid, [self._arg[i]], context=context)[self._arg[i]]
834             self._relations.append({
835                 'object': obj_name,
836                 'type': f['type']
837
838             })
839             if f.get('relation',False):
840                 obj_name = f['relation']
841                 self._relations[-1]['relation'] = f['relation']
842
843 # ---------------------------------------------------------
844 # Dummy fields
845 # ---------------------------------------------------------
846
847 class dummy(function):
848     def _fnct_search(self, tobj, cr, uid, obj=None, name=None, domain=None, context={}):
849         return []
850
851     def _fnct_write(self,obj,cr, uid, ids, field_name, values, args, context=None):
852         return False
853
854     def _fnct_read(self, obj, cr, uid, ids, field_name, args, context=None):
855         return {}
856
857     def __init__(self, *arg, **args):
858         self.arg = arg
859         self._relations = []
860         super(dummy, self).__init__(self._fnct_read, arg, self._fnct_write, fnct_inv_arg=arg, method=True, fnct_search=None, **args)
861
862 # ---------------------------------------------------------
863 # Serialized fields
864 # ---------------------------------------------------------
865 class serialized(_column):
866     def __init__(self, string='unknown', serialize_func=repr, deserialize_func=eval, type='text', **args):
867         self._serialize_func = serialize_func
868         self._deserialize_func = deserialize_func
869         self._type = type
870         self._symbol_set = (self._symbol_c, self._serialize_func)
871         self._symbol_get = self._deserialize_func
872         super(serialized, self).__init__(string=string, **args)
873
874
875 # TODO: review completly this class for speed improvement
876 class property(function):
877
878     def _get_default(self, obj, cr, uid, prop_name, context=None):
879         return self._get_defaults(obj, cr, uid, [prop_name], context=None)[prop_name]
880
881     def _get_defaults(self, obj, cr, uid, prop_name, context=None):
882         prop = obj.pool.get('ir.property')
883         domain = [('fields_id.model', '=', obj._name), ('fields_id.name','in',prop_name), ('res_id','=',False)]
884         ids = prop.search(cr, uid, domain, order='company_id', context=context)
885         default_value = {}.fromkeys(prop_name, False)
886         for prop_rec in prop.browse(cr, uid, ids, context=context):
887             if prop_rec.fields_id.name in default_value:
888                 continue
889             default_value[prop_rec.fields_id.name] = prop.get_by_record(cr, uid, prop_rec, context=context) or False
890         return default_value
891
892     def _get_by_id(self, obj, cr, uid, prop_name, ids, context=None):
893         prop = obj.pool.get('ir.property')
894         vids = [obj._name + ',' + str(oid) for oid in  ids]
895
896         domain = prop._get_domain(cr, uid, prop_name, obj._name, context)
897         if domain is not None:
898             domain = [('res_id', 'in', vids)] + domain
899             return prop.search(cr, uid, domain, context=context)
900         else:
901             return []
902
903
904     # TODO: to rewrite more clean
905     def _fnct_write(self, obj, cr, uid, id, prop_name, id_val, obj_dest, context=None):
906         if context is None:
907             context = {}
908
909         nids = self._get_by_id(obj, cr, uid, prop_name, [id], context)
910         if nids:
911             cr.execute('DELETE FROM ir_property WHERE id IN %s', (tuple(nids),))
912
913         default_val = self._get_default(obj, cr, uid, prop_name, context)
914
915         if id_val is not default_val:
916             def_id = self._field_get(cr, uid, obj._name, prop_name)
917             company = obj.pool.get('res.company')
918             cid = company._company_default_get(cr, uid, obj._name, def_id,
919                                                context=context)
920             propdef = obj.pool.get('ir.model.fields').browse(cr, uid, def_id,
921                                                              context=context)
922             prop = obj.pool.get('ir.property')
923             return prop.create(cr, uid, {
924                 'name': propdef.name,
925                 'value': id_val,
926                 'res_id': obj._name+','+str(id),
927                 'company_id': cid,
928                 'fields_id': def_id,
929                 'type': self._type,
930                 }, context=context)
931         return False
932
933
934     def _fnct_read(self, obj, cr, uid, ids, prop_name, obj_dest, context=None):
935         properties = obj.pool.get('ir.property')
936         domain = [('fields_id.model', '=', obj._name), ('fields_id.name','in',prop_name)]
937         domain += [('res_id','in', [obj._name + ',' + str(oid) for oid in  ids])]
938         nids = properties.search(cr, uid, domain, context=context)
939         default_val = self._get_defaults(obj, cr, uid, prop_name, context)
940
941         res = {}
942         for id in ids:
943             res[id] = default_val.copy()
944
945         replaces = {}
946         brs = properties.browse(cr, uid, nids, context=context)
947         for prop in brs:
948             value = properties.get_by_record(cr, uid, prop, context=context)
949             res[prop.res_id.id][prop.fields_id.name] = value or False
950             if value:
951                 replaces.setdefault(value._name, {})
952                 replaces[value._name][value.id] = True
953
954         for rep in replaces:
955             replaces[rep] = dict(obj.pool.get(rep).name_get(cr, uid, replaces[rep].keys(), context=context))
956
957         for prop in brs:
958             if prop.type == 'many2one':
959                 for id in ids:
960                     if res[id][prop.fields_id.name]:
961                         res[id][prop.fields_id.name] = replaces[res[id][prop.fields_id.name]._name].get(res[id][prop.fields_id.name], False)
962
963         return res
964
965
966     def _field_get(self, cr, uid, model_name, prop):
967         if not self.field_id.get(cr.dbname):
968             cr.execute('SELECT id \
969                     FROM ir_model_fields \
970                     WHERE name=%s AND model=%s', (prop, model_name))
971             res = cr.fetchone()
972             self.field_id[cr.dbname] = res and res[0]
973         return self.field_id[cr.dbname]
974
975     def __init__(self, obj_prop, **args):
976         # TODO remove obj_prop parameter (use many2one type)
977         self.field_id = {}
978         function.__init__(self, self._fnct_read, False, self._fnct_write,
979                           obj_prop, multi='properties', **args)
980
981     def restart(self):
982         self.field_id = {}
983
984
985 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
986