[FIX] properties
[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         # we use uid=1 because the visibility of a many2one field value (just id and name)
318         # must be the access right of the parent form and not the linked object itself.
319         records = dict(obj.name_get(cr, 1, list(set(filter(None, res.values()))), context=context))
320         for id in res:
321             if res[id] in records:
322                 res[id] = (res[id], records[res[id]])
323             else:
324                 res[id] = False
325         return res
326
327     def set(self, cr, obj_src, id, field, values, user=None, context=None):
328         if not context:
329             context = {}
330         obj = obj_src.pool.get(self._obj)
331         self._table = obj_src.pool.get(self._obj)._table
332         if type(values) == type([]):
333             for act in values:
334                 if act[0] == 0:
335                     id_new = obj.create(cr, act[2])
336                     cr.execute('update '+obj_src._table+' set '+field+'=%s where id=%s', (id_new, id))
337                 elif act[0] == 1:
338                     obj.write(cr, [act[1]], act[2], context=context)
339                 elif act[0] == 2:
340                     cr.execute('delete from '+self._table+' where id=%s', (act[1],))
341                 elif act[0] == 3 or act[0] == 5:
342                     cr.execute('update '+obj_src._table+' set '+field+'=null where id=%s', (id,))
343                 elif act[0] == 4:
344                     cr.execute('update '+obj_src._table+' set '+field+'=%s where id=%s', (act[1], id))
345         else:
346             if values:
347                 cr.execute('update '+obj_src._table+' set '+field+'=%s where id=%s', (values, id))
348             else:
349                 cr.execute('update '+obj_src._table+' set '+field+'=null where id=%s', (id,))
350
351     def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, context=None):
352         return obj.pool.get(self._obj).search(cr, uid, args+self._domain+[('name', 'like', value)], offset, limit, context=context)
353
354
355 class one2many(_column):
356     _classic_read = False
357     _classic_write = False
358     _prefetch = False
359     _type = 'one2many'
360
361     def __init__(self, obj, fields_id, string='unknown', limit=None, **args):
362         _column.__init__(self, string=string, **args)
363         self._obj = obj
364         self._fields_id = fields_id
365         self._limit = limit
366         #one2many can't be used as condition for defaults
367         assert(self.change_default != True)
368
369     def get_memory(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
370         if not context:
371             context = {}
372         if self._context:
373             context = context.copy()
374             context.update(self._context)
375         if not values:
376             values = {}
377         res = {}
378         for id in ids:
379             res[id] = []
380         ids2 = obj.pool.get(self._obj).search(cr, user, [(self._fields_id, 'in', ids)], limit=self._limit, context=context)
381         for r in obj.pool.get(self._obj).read(cr, user, ids2, [self._fields_id], context=context, load='_classic_write'):
382             if r[self._fields_id] in res:
383                 res[r[self._fields_id]].append(r['id'])
384         return res
385
386     def set_memory(self, cr, obj, id, field, values, user=None, context=None):
387         if not context:
388             context = {}
389         if self._context:
390             context = context.copy()
391         context.update(self._context)
392         if not values:
393             return
394         obj = obj.pool.get(self._obj)
395         for act in values:
396             if act[0] == 0:
397                 act[2][self._fields_id] = id
398                 obj.create(cr, user, act[2], context=context)
399             elif act[0] == 1:
400                 obj.write(cr, user, [act[1]], act[2], context=context)
401             elif act[0] == 2:
402                 obj.unlink(cr, user, [act[1]], context=context)
403             elif act[0] == 3:
404                 obj.datas[act[1]][self._fields_id] = False
405             elif act[0] == 4:
406                 obj.datas[act[1]] = id
407             elif act[0] == 5:
408                 for o in obj.datas.values():
409                     if o[self._fields_id] == id:
410                         o[self._fields_id] = False
411             elif act[0] == 6:
412                 for id2 in (act[2] or []):
413                     obj.datas[id2][self._fields_id] = id
414
415     def search_memory(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, operator='like', context=None):
416         raise _('Not Implemented')
417
418     def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
419         if not context:
420             context = {}
421         if self._context:
422             context = context.copy()
423         context.update(self._context)
424         if not values:
425             values = {}
426
427         res = defaultdict(list)
428
429         ids2 = obj.pool.get(self._obj).search(cr, user, self._domain + [(self._fields_id, 'in', ids)], limit=self._limit, context=context)
430         for r in obj.pool.get(self._obj)._read_flat(cr, user, ids2, [self._fields_id], context=context, load='_classic_write'):
431             res[r[self._fields_id]].append(r['id'])
432         return res
433
434     def set(self, cr, obj, id, field, values, user=None, context=None):
435         result = []
436         if not context:
437             context = {}
438         if self._context:
439             context = context.copy()
440         context.update(self._context)
441         context['no_store_function'] = True
442         if not values:
443             return
444         _table = obj.pool.get(self._obj)._table
445         obj = obj.pool.get(self._obj)
446         for act in values:
447             if act[0] == 0:
448                 act[2][self._fields_id] = id
449                 id_new = obj.create(cr, user, act[2], context=context)
450                 result += obj._store_get_values(cr, user, [id_new], act[2].keys(), context)
451             elif act[0] == 1:
452                 obj.write(cr, user, [act[1]], act[2], context=context)
453             elif act[0] == 2:
454                 obj.unlink(cr, user, [act[1]], context=context)
455             elif act[0] == 3:
456                 cr.execute('update '+_table+' set '+self._fields_id+'=null where id=%s', (act[1],))
457             elif act[0] == 4:
458                 cr.execute('update '+_table+' set '+self._fields_id+'=%s where id=%s', (id, act[1]))
459             elif act[0] == 5:
460                 cr.execute('update '+_table+' set '+self._fields_id+'=null where '+self._fields_id+'=%s', (id,))
461             elif act[0] == 6:
462                 obj.write(cr, user, act[2], {self._fields_id:id}, context=context or {})
463                 ids2 = act[2] or [0]
464                 cr.execute('select id from '+_table+' where '+self._fields_id+'=%s and id <> ALL (%s)', (id,ids2))
465                 ids3 = map(lambda x:x[0], cr.fetchall())
466                 obj.write(cr, user, ids3, {self._fields_id:False}, context=context or {})
467         return result
468
469     def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, operator='like', context=None):
470         return obj.pool.get(self._obj).name_search(cr, uid, value, self._domain, operator, context=context,limit=limit)
471
472
473 #
474 # Values: (0, 0,  { fields })    create
475 #         (1, ID, { fields })    update (write fields to ID)
476 #         (2, ID)                remove (calls unlink on ID, that will also delete the relationship because of the ondelete)
477 #         (3, ID)                unlink (delete the relationship between the two objects but does not delete ID)
478 #         (4, ID)                link (add a relationship)
479 #         (5, ID)                unlink all
480 #         (6, ?, ids)            set a list of links
481 #
482 class many2many(_column):
483     _classic_read = False
484     _classic_write = False
485     _prefetch = False
486     _type = 'many2many'
487     def __init__(self, obj, rel, id1, id2, string='unknown', limit=None, **args):
488         _column.__init__(self, string=string, **args)
489         self._obj = obj
490         if '.' in rel:
491             raise Exception(_('The second argument of the many2many field %s must be a SQL table !'\
492                 'You used %s, which is not a valid SQL table name.')% (string,rel))
493         self._rel = rel
494         self._id1 = id1
495         self._id2 = id2
496         self._limit = limit
497
498     def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
499         if not context:
500             context = {}
501         if not values:
502             values = {}
503         res = {}
504         if not ids:
505             return res
506         for id in ids:
507             res[id] = []
508         limit_str = self._limit is not None and ' limit %d' % self._limit or ''
509         obj = obj.pool.get(self._obj)
510
511         d1, d2, tables = obj.pool.get('ir.rule').domain_get(cr, user, obj._name, context=context)
512         if d1:
513             d1 = ' and ' + ' and '.join(d1)
514         else: d1 = ''
515         query = 'SELECT %(rel)s.%(id2)s, %(rel)s.%(id1)s \
516                    FROM %(rel)s, %(tbl)s \
517                   WHERE %(rel)s.%(id1)s in %%s \
518                     AND %(rel)s.%(id2)s = %(tbl)s.id \
519                  %(d1)s  \
520                  %(limit)s \
521                   ORDER BY %(tbl)s.%(order)s \
522                  OFFSET %(offset)d' \
523             % {'rel': self._rel,
524                'tbl': obj._table,
525                'id1': self._id1,
526                'id2': self._id2,
527                'd1': d1,
528                'limit': limit_str,
529                'order': obj._order,
530                'offset': offset,
531               }
532         cr.execute(query, [tuple(ids)] + d2)
533         for r in cr.fetchall():
534             res[r[1]].append(r[0])
535         return res
536
537     def set(self, cr, obj, id, name, values, user=None, context=None):
538         if not context:
539             context = {}
540         if not values:
541             return
542         obj = obj.pool.get(self._obj)
543         for act in values:
544             if not (isinstance(act, list) or isinstance(act, tuple)) or not act:
545                 continue
546             if act[0] == 0:
547                 idnew = obj.create(cr, user, act[2])
548                 cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%s,%s)', (id, idnew))
549             elif act[0] == 1:
550                 obj.write(cr, user, [act[1]], act[2], context=context)
551             elif act[0] == 2:
552                 obj.unlink(cr, user, [act[1]], context=context)
553             elif act[0] == 3:
554                 cr.execute('delete from '+self._rel+' where ' + self._id1 + '=%s and '+ self._id2 + '=%s', (id, act[1]))
555             elif act[0] == 4:
556                 cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%s,%s)', (id, act[1]))
557             elif act[0] == 5:
558                 cr.execute('update '+self._rel+' set '+self._id2+'=null where '+self._id2+'=%s', (id,))
559             elif act[0] == 6:
560
561                 d1, d2,tables = obj.pool.get('ir.rule').domain_get(cr, user, obj._name, context=context)
562                 if d1:
563                     d1 = ' and ' + ' and '.join(d1)
564                 else:
565                     d1 = ''
566                 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)
567
568                 for act_nbr in act[2]:
569                     cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%s, %s)', (id, act_nbr))
570
571     #
572     # TODO: use a name_search
573     #
574     def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, operator='like', context=None):
575         return obj.pool.get(self._obj).search(cr, uid, args+self._domain+[('name', operator, value)], offset, limit, context=context)
576
577     def get_memory(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
578         result = {}
579         for id in ids:
580             result[id] = obj.datas[id].get(name, [])
581         return result
582
583     def set_memory(self, cr, obj, id, name, values, user=None, context=None):
584         if not values:
585             return
586         for act in values:
587             # TODO: use constants instead of these magic numbers
588             if act[0] == 0:
589                 raise _('Not Implemented')
590             elif act[0] == 1:
591                 raise _('Not Implemented')
592             elif act[0] == 2:
593                 raise _('Not Implemented')
594             elif act[0] == 3:
595                 raise _('Not Implemented')
596             elif act[0] == 4:
597                 raise _('Not Implemented')
598             elif act[0] == 5:
599                 raise _('Not Implemented')
600             elif act[0] == 6:
601                 obj.datas[id][name] = act[2]
602
603
604 def get_nice_size(a):
605     (x,y) = a
606     if isinstance(y, (int,long)):
607         size = y
608     elif y:
609         size = len(y)
610     else:
611         size = 0
612     return (x, tools.human_size(size))
613
614 # ---------------------------------------------------------
615 # Function fields
616 # ---------------------------------------------------------
617 class function(_column):
618     _classic_read = False
619     _classic_write = False
620     _prefetch = False
621     _type = 'function'
622     _properties = True
623
624 #
625 # multi: compute several fields in one call
626 #
627     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):
628         _column.__init__(self, **args)
629         self._obj = obj
630         self._method = method
631         self._fnct = fnct
632         self._fnct_inv = fnct_inv
633         self._arg = arg
634         self._multi = multi
635         if 'relation' in args:
636             self._obj = args['relation']
637
638         self.digits = args.get('digits', (16,2))
639         self.digits_compute = args.get('digits_compute', None)
640
641         self._fnct_inv_arg = fnct_inv_arg
642         if not fnct_inv:
643             self.readonly = 1
644         self._type = type
645         self._fnct_search = fnct_search
646         self.store = store
647
648         if not fnct_search and not store:
649             self.selectable = False
650
651         if store:
652             if self._type != 'many2one':
653                 # m2o fields need to return tuples with name_get, not just foreign keys
654                 self._classic_read = True
655             self._classic_write = True
656             if type=='binary':
657                 self._symbol_get=lambda x:x and str(x)
658
659         if type == 'float':
660             self._symbol_c = float._symbol_c
661             self._symbol_f = float._symbol_f
662             self._symbol_set = float._symbol_set
663
664         if type == 'boolean':
665             self._symbol_c = boolean._symbol_c
666             self._symbol_f = boolean._symbol_f
667             self._symbol_set = boolean._symbol_set
668
669     def digits_change(self, cr):
670         if self.digits_compute:
671             t = self.digits_compute(cr)
672             self._symbol_set=('%s', lambda x: ('%.'+str(t[1])+'f') % (__builtin__.float(x or 0.0),))
673             self.digits = t
674
675
676     def search(self, cr, uid, obj, name, args, context=None):
677         if not self._fnct_search:
678             #CHECKME: should raise an exception
679             return []
680         return self._fnct_search(obj, cr, uid, obj, name, args, context=context)
681
682     def get(self, cr, obj, ids, name, user=None, context=None, values=None):
683         if not context:
684             context = {}
685         if not values:
686             values = {}
687         res = {}
688         if self._method:
689             res = self._fnct(obj, cr, user, ids, name, self._arg, context)
690         else:
691             res = self._fnct(cr, obj._table, ids, name, self._arg, context)
692
693         if self._type == "many2one" :
694             # Filtering only integer/long values if passed
695             res_ids = [x for x in res.values() if x and isinstance(x, (int,long))]
696
697             if res_ids:
698                 obj_model = obj.pool.get(self._obj)
699                 dict_names = dict(obj_model.name_get(cr, user, res_ids, context))
700                 for r in res.keys():
701                     if res[r] and res[r] in dict_names:
702                         res[r] = (res[r], dict_names[res[r]])
703
704         if self._type == 'binary' and context.get('bin_size', False):
705             # convert the data returned by the function with the size of that data...
706             res = dict(map( get_nice_size, res.items()))
707         if self._type == "integer":
708             for r in res.keys():
709                 # Converting value into string so that it does not affect XML-RPC Limits
710                 if isinstance(res[r],dict): # To treat integer values with _multi attribute
711                     for record in res[r].keys():
712                         res[r][record] = str(res[r][record])
713                 else:
714                     res[r] = str(res[r])
715         return res
716     get_memory = get
717
718     def set(self, cr, obj, id, name, value, user=None, context=None):
719         if not context:
720             context = {}
721         if self._fnct_inv:
722             self._fnct_inv(obj, cr, user, id, name, value, self._fnct_inv_arg, context)
723     set_memory = set
724
725 # ---------------------------------------------------------
726 # Related fields
727 # ---------------------------------------------------------
728
729 class related(function):
730
731     def _fnct_search(self, tobj, cr, uid, obj=None, name=None, domain=None, context={}):
732         self._field_get2(cr, uid, obj, context)
733         i = len(self._arg)-1
734         sarg = name
735         while i>0:
736             if type(sarg) in [type([]), type( (1,) )]:
737                 where = [(self._arg[i], 'in', sarg)]
738             else:
739                 where = [(self._arg[i], '=', sarg)]
740             if domain:
741                 where = map(lambda x: (self._arg[i],x[1], x[2]), domain)
742                 domain = []
743             sarg = obj.pool.get(self._relations[i]['object']).search(cr, uid, where, context=context)
744             i -= 1
745         return [(self._arg[0], 'in', sarg)]
746
747     def _fnct_write(self,obj,cr, uid, ids, field_name, values, args, context=None):
748         self._field_get2(cr, uid, obj, context)
749         if type(ids) != type([]):
750             ids=[ids]
751         objlst = obj.browse(cr, uid, ids)
752         for data in objlst:
753             t_id = data.id
754             t_data = data
755             for i in range(len(self.arg)):
756                 if not t_data: break
757                 field_detail = self._relations[i]
758                 if not t_data[self.arg[i]]:
759                     if self._type not in ('one2many', 'many2many'):
760                         t_id = t_data['id']
761                     t_data = False
762                 elif field_detail['type'] in ('one2many', 'many2many'):
763                     if self._type != "many2one":
764                         t_id = t_data.id
765                         t_data = t_data[self.arg[i]][0]
766                     else:
767                         t_data = False
768                 else:
769                     t_id = t_data['id']
770                     t_data = t_data[self.arg[i]]
771             else:
772                 model = obj.pool.get(self._relations[-1]['object'])
773                 model.write(cr, uid, [t_id], {args[-1]: values}, context=context)
774
775     def _fnct_read(self, obj, cr, uid, ids, field_name, args, context=None):
776         self._field_get2(cr, uid, obj, context)
777         if not ids: return {}
778         relation = obj._name
779         if self._type in ('one2many', 'many2many'):
780             res = {}.fromkeys(ids, [])
781         else:
782             res = {}.fromkeys(ids, False)
783
784         objlst = obj.browse(cr, 1, ids, context=context)
785         for data in objlst:
786             if not data:
787                 continue
788             t_data = data
789             relation = obj._name
790             for i in range(len(self.arg)):
791                 field_detail = self._relations[i]
792                 relation = field_detail['object']
793                 try:
794                     if not t_data[self.arg[i]]:
795                         t_data = False
796                         break
797                 except:
798                     t_data = False
799                     break
800                 if field_detail['type'] in ('one2many', 'many2many') and i != len(self.arg) - 1:
801                     t_data = t_data[self.arg[i]][0]
802                 elif t_data:
803                     t_data = t_data[self.arg[i]]
804             if type(t_data) == type(objlst[0]):
805                 res[data.id] = t_data.id
806             elif t_data:
807                 res[data.id] = t_data
808         if self._type=='many2one':
809             ids = filter(None, res.values())
810             if ids:
811                 ng = dict(obj.pool.get(self._obj).name_get(cr, 1, ids, context=context))
812                 for r in res:
813                     if res[r]:
814                         res[r] = (res[r], ng[res[r]])
815         elif self._type in ('one2many', 'many2many'):
816             for r in res:
817                 if res[r]:
818                     res[r] = [x.id for x in res[r]]
819         return res
820
821     def __init__(self, *arg, **args):
822         self.arg = arg
823         self._relations = []
824         super(related, self).__init__(self._fnct_read, arg, self._fnct_write, fnct_inv_arg=arg, method=True, fnct_search=self._fnct_search, **args)
825         if self.store is True:
826             # TODO: improve here to change self.store = {...} according to related objects
827             pass
828
829     def _field_get2(self, cr, uid, obj, context={}):
830         if self._relations:
831             return
832         obj_name = obj._name
833         for i in range(len(self._arg)):
834             f = obj.pool.get(obj_name).fields_get(cr, uid, [self._arg[i]], context=context)[self._arg[i]]
835             self._relations.append({
836                 'object': obj_name,
837                 'type': f['type']
838
839             })
840             if f.get('relation',False):
841                 obj_name = f['relation']
842                 self._relations[-1]['relation'] = f['relation']
843
844 # ---------------------------------------------------------
845 # Dummy fields
846 # ---------------------------------------------------------
847
848 class dummy(function):
849     def _fnct_search(self, tobj, cr, uid, obj=None, name=None, domain=None, context={}):
850         return []
851
852     def _fnct_write(self,obj,cr, uid, ids, field_name, values, args, context=None):
853         return False
854
855     def _fnct_read(self, obj, cr, uid, ids, field_name, args, context=None):
856         return {}
857
858     def __init__(self, *arg, **args):
859         self.arg = arg
860         self._relations = []
861         super(dummy, self).__init__(self._fnct_read, arg, self._fnct_write, fnct_inv_arg=arg, method=True, fnct_search=None, **args)
862
863 # ---------------------------------------------------------
864 # Serialized fields
865 # ---------------------------------------------------------
866 class serialized(_column):
867     def __init__(self, string='unknown', serialize_func=repr, deserialize_func=eval, type='text', **args):
868         self._serialize_func = serialize_func
869         self._deserialize_func = deserialize_func
870         self._type = type
871         self._symbol_set = (self._symbol_c, self._serialize_func)
872         self._symbol_get = self._deserialize_func
873         super(serialized, self).__init__(string=string, **args)
874
875
876 # TODO: review completly this class for speed improvement
877 class property(function):
878
879     def _get_default(self, obj, cr, uid, prop_name, context=None):
880         return self._get_defaults(obj, cr, uid, [prop_name], context=None)[0][prop_name]
881
882     def _get_defaults(self, obj, cr, uid, prop_name, context=None):
883         prop = obj.pool.get('ir.property')
884         domain = [('fields_id.model', '=', obj._name), ('fields_id.name','in',prop_name), ('res_id','=',False)]
885         ids = prop.search(cr, uid, domain, order='company_id', context=context)
886         replaces = {}
887         default_value = {}.fromkeys(prop_name, False)
888         for prop_rec in prop.browse(cr, uid, ids, context=context):
889             if default_value.get(prop_rec.fields_id.name, False):
890                 continue
891             value = prop.get_by_record(cr, uid, prop_rec, context=context) or False
892             default_value[prop_rec.fields_id.name] = value
893             if value and (prop_rec.type == 'many2one'):
894                 replaces.setdefault(value._name, {})
895                 replaces[value._name][value.id] = True
896         return default_value, replaces
897
898     def _get_by_id(self, obj, cr, uid, prop_name, ids, context=None):
899         prop = obj.pool.get('ir.property')
900         vids = [obj._name + ',' + str(oid) for oid in  ids]
901
902         domain = [('fields_id.model', '=', obj._name), ('fields_id.name','in',prop_name)]
903         #domain = prop._get_domain(cr, uid, prop_name, obj._name, context)
904         if domain is not None:
905             domain = [('res_id', 'in', vids)] + domain
906             return prop.search(cr, uid, domain, context=context)
907         else:
908             return []
909
910
911     # TODO: to rewrite more clean
912     def _fnct_write(self, obj, cr, uid, id, prop_name, id_val, obj_dest, context=None):
913         if context is None:
914             context = {}
915
916         nids = self._get_by_id(obj, cr, uid, [prop_name], [id], context)
917         if nids:
918             cr.execute('DELETE FROM ir_property WHERE id IN %s', (tuple(nids),))
919
920         default_val = self._get_default(obj, cr, uid, prop_name, context)
921
922         if id_val is not default_val:
923             def_id = self._field_get(cr, uid, obj._name, prop_name)
924             company = obj.pool.get('res.company')
925             cid = company._company_default_get(cr, uid, obj._name, def_id,
926                                                context=context)
927             propdef = obj.pool.get('ir.model.fields').browse(cr, uid, def_id,
928                                                              context=context)
929             prop = obj.pool.get('ir.property')
930             return prop.create(cr, uid, {
931                 'name': propdef.name,
932                 'value': id_val,
933                 'res_id': obj._name+','+str(id),
934                 'company_id': cid,
935                 'fields_id': def_id,
936                 'type': self._type,
937             }, context=context)
938         return False
939
940
941     def _fnct_read(self, obj, cr, uid, ids, prop_name, obj_dest, context=None):
942         properties = obj.pool.get('ir.property')
943         domain = [('fields_id.model', '=', obj._name), ('fields_id.name','in',prop_name)]
944         domain += [('res_id','in', [obj._name + ',' + str(oid) for oid in  ids])]
945         nids = properties.search(cr, uid, domain, context=context)
946         default_val,replaces = self._get_defaults(obj, cr, uid, prop_name, context)
947
948         res = {}
949         for id in ids:
950             res[id] = default_val.copy()
951
952         brs = properties.browse(cr, uid, nids, context=context)
953         for prop in brs:
954             value = properties.get_by_record(cr, uid, prop, context=context)
955             res[prop.res_id.id][prop.fields_id.name] = value or False
956             if value and (prop.type == 'many2one'):
957                 replaces.setdefault(value._name, {})
958                 replaces[value._name][value.id] = True
959
960         for rep in replaces:
961             replaces[rep] = dict(obj.pool.get(rep).name_get(cr, uid, replaces[rep].keys(), context=context))
962
963         for prop in prop_name:
964             for id in ids:
965                 if res[id][prop] and hasattr(res[id][prop], '_name'):
966                     res[id][prop] = (res[id][prop].id , replaces[res[id][prop]._name].get(res[id][prop].id, False))
967
968         return res
969
970
971     def _field_get(self, cr, uid, model_name, prop):
972         if not self.field_id.get(cr.dbname):
973             cr.execute('SELECT id \
974                     FROM ir_model_fields \
975                     WHERE name=%s AND model=%s', (prop, model_name))
976             res = cr.fetchone()
977             self.field_id[cr.dbname] = res and res[0]
978         return self.field_id[cr.dbname]
979
980     def __init__(self, obj_prop, **args):
981         # TODO remove obj_prop parameter (use many2one type)
982         self.field_id = {}
983         function.__init__(self, self._fnct_read, False, self._fnct_write,
984                           obj_prop, multi='properties', **args)
985
986     def restart(self):
987         self.field_id = {}
988
989
990 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
991