[IMP] better view, no NULL value for int and float
[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 import string
35 import netsvc
36 import sys
37
38 from psycopg2 import Binary
39 import warnings
40
41 import tools
42
43
44 def _symbol_set(symb):
45     if symb == None or symb == False:
46         return None
47     elif isinstance(symb, unicode):
48         return symb.encode('utf-8')
49     return str(symb)
50
51
52 class _column(object):
53     _classic_read = True
54     _classic_write = True
55     _prefetch = True
56     _properties = False
57     _type = 'unknown'
58     _obj = None
59     _multi = False
60     _symbol_c = '%s'
61     _symbol_f = _symbol_set
62     _symbol_set = (_symbol_c, _symbol_f)
63     _symbol_get = None
64
65     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):
66         self.states = states or {}
67         self.string = string
68         self.readonly = readonly
69         self.required = required
70         self.size = size
71         self.help = args.get('help', '')
72         self.priority = priority
73         self.change_default = change_default
74         self.ondelete = ondelete
75         self.translate = translate
76         self._domain = domain or []
77         self._context = context
78         self.write = False
79         self.read = False
80         self.view_load = 0
81         self.select = select
82         self.selectable = True
83         self.group_operator = args.get('group_operator', False)
84         self.parent_field = args.get('parent_field', 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 })    modification
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][name]
303         return result
304
305     def get(self, cr, obj, ids, name, user=None, context=None, values=None):
306         if not context:
307             context = {}
308         if not values:
309             values = {}
310         res = {}
311         for r in values:
312             res[r['id']] = r[name]
313         for id in ids:
314             res.setdefault(id, '')
315         obj = obj.pool.get(self._obj)
316
317         # build a dictionary of the form {'id_of_distant_resource': name_of_distant_resource}
318         from orm import except_orm
319         names = {}
320         for record in list(set(filter(None, res.values()))):
321             try:
322                 record_name = dict(obj.name_get(cr, user, [record], context))
323             except except_orm:
324                 record_name = {}
325                 record_name[record] = '// Access Denied //'
326             names.update(record_name)
327
328         for r in res.keys():
329             if res[r] and res[r] in names:
330                 res[r] = (res[r], names[res[r]])
331             else:
332                 res[r] = False
333         return res
334
335     def set(self, cr, obj_src, id, field, values, user=None, context=None):
336         if not context:
337             context = {}
338         obj = obj_src.pool.get(self._obj)
339         self._table = obj_src.pool.get(self._obj)._table
340         if type(values) == type([]):
341             for act in values:
342                 if act[0] == 0:
343                     id_new = obj.create(cr, act[2])
344                     cr.execute('update '+obj_src._table+' set '+field+'=%s where id=%s', (id_new, id))
345                 elif act[0] == 1:
346                     obj.write(cr, [act[1]], act[2], context=context)
347                 elif act[0] == 2:
348                     cr.execute('delete from '+self._table+' where id=%s', (act[1],))
349                 elif act[0] == 3 or act[0] == 5:
350                     cr.execute('update '+obj_src._table+' set '+field+'=null where id=%s', (id,))
351                 elif act[0] == 4:
352                     cr.execute('update '+obj_src._table+' set '+field+'=%s where id=%s', (act[1], id))
353         else:
354             if values:
355                 cr.execute('update '+obj_src._table+' set '+field+'=%s where id=%s', (values, id))
356             else:
357                 cr.execute('update '+obj_src._table+' set '+field+'=null where id=%s', (id,))
358
359     def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, context=None):
360         return obj.pool.get(self._obj).search(cr, uid, args+self._domain+[('name', 'like', value)], offset, limit, context=context)
361
362
363 class one2many(_column):
364     _classic_read = False
365     _classic_write = False
366     _prefetch = False
367     _type = 'one2many'
368
369     def __init__(self, obj, fields_id, string='unknown', limit=None, **args):
370         args.update({'parent_field':fields_id})
371         _column.__init__(self, string=string, **args)
372         self._obj = obj
373         self._fields_id = fields_id
374         self._limit = limit
375         #one2many can't be used as condition for defaults
376         assert(self.change_default != True)
377
378     def get_memory(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
379         if not context:
380             context = {}
381         if self._context:
382             context = context.copy()
383             context.update(self._context)
384         if not values:
385             values = {}
386         res = {}
387         for id in ids:
388             res[id] = []
389         ids2 = obj.pool.get(self._obj).search(cr, user, [(self._fields_id, 'in', ids)], limit=self._limit, context=context)
390         for r in obj.pool.get(self._obj).read(cr, user, ids2, [self._fields_id], context=context, load='_classic_write'):
391             if r[self._fields_id] in res:
392                 res[r[self._fields_id]].append(r['id'])
393         return res
394
395     def set_memory(self, cr, obj, id, field, values, user=None, context=None):
396         if not context:
397             context = {}
398         if self._context:
399             context = context.copy()
400         context.update(self._context)
401         if not values:
402             return
403         obj = obj.pool.get(self._obj)
404         for act in values:
405             if act[0] == 0:
406                 act[2][self._fields_id] = id
407                 obj.create(cr, user, act[2], context=context)
408             elif act[0] == 1:
409                 obj.write(cr, user, [act[1]], act[2], context=context)
410             elif act[0] == 2:
411                 obj.unlink(cr, user, [act[1]], context=context)
412             elif act[0] == 3:
413                 obj.datas[act[1]][self._fields_id] = False
414             elif act[0] == 4:
415                 obj.datas[act[1]] = id
416             elif act[0] == 5:
417                 for o in obj.datas.values():
418                     if o[self._fields_id] == id:
419                         o[self._fields_id] = False
420             elif act[0] == 6:
421                 for id2 in (act[2] or []):
422                     obj.datas[id2][self._fields_id] = id
423
424     def search_memory(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, operator='like', context=None):
425         raise _('Not Implemented')
426
427     def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
428         if not context:
429             context = {}
430         if self._context:
431             context = context.copy()
432         context.update(self._context)
433         if not values:
434             values = {}
435         res = {}
436         for id in ids:
437             res[id] = []
438         ids2 = obj.pool.get(self._obj).search(cr, user, [(self._fields_id, 'in', ids)], limit=self._limit, context=context)
439         for r in obj.pool.get(self._obj)._read_flat(cr, user, ids2, [self._fields_id], context=context, load='_classic_write'):
440             res[r[self._fields_id]].append(r['id'])
441         return res
442
443     def set(self, cr, obj, id, field, values, user=None, context=None):
444         result = []
445         if not context:
446             context = {}
447         if self._context:
448             context = context.copy()
449         context.update(self._context)
450         context['no_store_function'] = True
451         if not values:
452             return
453         _table = obj.pool.get(self._obj)._table
454         obj = obj.pool.get(self._obj)
455         for act in values:
456             if act[0] == 0:
457                 act[2][self._fields_id] = id
458                 id_new = obj.create(cr, user, act[2], context=context)
459                 result += obj._store_get_values(cr, user, [id_new], act[2].keys(), context)
460             elif act[0] == 1:
461                 obj.write(cr, user, [act[1]], act[2], context=context)
462             elif act[0] == 2:
463                 obj.unlink(cr, user, [act[1]], context=context)
464             elif act[0] == 3:
465                 cr.execute('update '+_table+' set '+self._fields_id+'=null where id=%s', (act[1],))
466             elif act[0] == 4:
467                 cr.execute('update '+_table+' set '+self._fields_id+'=%s where id=%s', (id, act[1]))
468             elif act[0] == 5:
469                 cr.execute('update '+_table+' set '+self._fields_id+'=null where '+self._fields_id+'=%s', (id,))
470             elif act[0] == 6:
471                 obj.write(cr, user, act[2], {self._fields_id:id}, context=context or {})
472                 ids2 = act[2] or [0]
473                 cr.execute('select id from '+_table+' where '+self._fields_id+'=%s and id <> ALL (%s)', (id,ids2))
474                 ids3 = map(lambda x:x[0], cr.fetchall())
475                 obj.write(cr, user, ids3, {self._fields_id:False}, context=context or {})
476         return result
477
478     def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, operator='like', context=None):
479         return obj.pool.get(self._obj).name_search(cr, uid, value, self._domain, operator, context=context,limit=limit)
480
481
482 #
483 # Values: (0, 0,  { fields })    create
484 #         (1, ID, { fields })    modification
485 #         (2, ID)                remove
486 #         (3, ID)                unlink
487 #         (4, ID)                link
488 #         (5, ID)                unlink all
489 #         (6, ?, ids)            set a list of links
490 #
491 class many2many(_column):
492     _classic_read = False
493     _classic_write = False
494     _prefetch = False
495     _type = 'many2many'
496
497     def __init__(self, obj, rel, id1, id2, string='unknown', limit=None, **args):
498         _column.__init__(self, string=string, **args)
499         self._obj = obj
500         if '.' in rel:
501             raise Exception(_('The second argument of the many2many field %s must be a SQL table !'\
502                 'You used %s, which is not a valid SQL table name.')% (string,rel))
503         self._rel = rel
504         self._id1 = id1
505         self._id2 = id2
506         self._limit = limit
507
508     def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
509         if not context:
510             context = {}
511         if not values:
512             values = {}
513         res = {}
514         if not ids:
515             return res
516         for id in ids:
517             res[id] = []
518         limit_str = self._limit is not None and ' limit %d' % self._limit or ''
519         obj = obj.pool.get(self._obj)
520
521         d1, d2, tables = obj.pool.get('ir.rule').domain_get(cr, user, obj._name, context=context)
522         if d1:
523             d1 = ' and ' + ' and '.join(d1)
524         else: d1 = ''
525
526         cr.execute('SELECT '+self._rel+'.'+self._id2+','+self._rel+'.'+self._id1+' \
527                 FROM '+self._rel+' , '+(','.join(tables))+' \
528                 WHERE '+self._rel+'.'+self._id1+' = ANY (%s) \
529                     AND '+self._rel+'.'+self._id2+' = '+obj._table+'.id '+d1
530                 +limit_str+' order by '+obj._table+'.'+obj._order+' offset %s',
531                 [ids,]+d2+[offset])
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             self._classic_read = True
652             self._classic_write = True
653             if type=='binary':
654                 self._symbol_get=lambda x:x and str(x)
655
656         if type == 'float':
657             self._symbol_c = float._symbol_c
658             self._symbol_f = float._symbol_f
659             self._symbol_set = float._symbol_set
660
661     def digits_change(self, cr):
662         if self.digits_compute:
663             t = self.digits_compute(cr)
664             self._symbol_set=('%s', lambda x: ('%.'+str(t[1])+'f') % (__builtin__.float(x or 0.0),))
665             self.digits = t
666
667
668     def search(self, cr, uid, obj, name, args, context=None):
669         if not self._fnct_search:
670             #CHECKME: should raise an exception
671             return []
672         return self._fnct_search(obj, cr, uid, obj, name, args, context=context)
673
674     def get(self, cr, obj, ids, name, user=None, context=None, values=None):
675         if not context:
676             context = {}
677         if not values:
678             values = {}
679         res = {}
680         if self._method:
681             res = self._fnct(obj, cr, user, ids, name, self._arg, context)
682         else:
683             res = self._fnct(cr, obj._table, ids, name, self._arg, context)
684
685         if self._type == "many2one" :
686             # Filtering only integer/long values if passed
687             res_ids = [x for x in res.values() if x and isinstance(x, (int,long))]
688
689             if res_ids:
690                 obj_model = obj.pool.get(self._obj)
691                 dict_names = dict(obj_model.name_get(cr, user, res_ids, context))
692                 for r in res.keys():
693                     if res[r] and res[r] in dict_names:
694                         res[r] = (res[r], dict_names[res[r]])
695
696         if self._type == 'binary' and context.get('bin_size', False):
697             # convert the data returned by the function with the size of that data...
698             res = dict(map( get_nice_size, res.items()))
699         if self._type == "integer":
700             for r in res.keys():
701                 # Converting value into string so that it does not affect XML-RPC Limits
702                 if isinstance(res[r],dict): # To treat integer values with _multi attribute
703                     for record in res[r].keys():
704                         res[r][record] = str(res[r][record])
705                 else:
706                     res[r] = str(res[r])
707         return res
708     get_memory = get
709
710     def set(self, cr, obj, id, name, value, user=None, context=None):
711         if not context:
712             context = {}
713         if self._fnct_inv:
714             self._fnct_inv(obj, cr, user, id, name, value, self._fnct_inv_arg, context)
715     set_memory = set
716
717 # ---------------------------------------------------------
718 # Related fields
719 # ---------------------------------------------------------
720
721 class related(function):
722
723     def _fnct_search(self, tobj, cr, uid, obj=None, name=None, domain=None, context={}):
724         self._field_get2(cr, uid, obj, context)
725         i = len(self._arg)-1
726         sarg = name
727         while i>0:
728             if type(sarg) in [type([]), type( (1,) )]:
729                 where = [(self._arg[i], 'in', sarg)]
730             else:
731                 where = [(self._arg[i], '=', sarg)]
732             if domain:
733                 where = map(lambda x: (self._arg[i],x[1], x[2]), domain)
734                 domain = []
735             sarg = obj.pool.get(self._relations[i]['object']).search(cr, uid, where, context=context)
736             i -= 1
737         return [(self._arg[0], 'in', sarg)]
738
739     def _fnct_write(self,obj,cr, uid, ids, field_name, values, args, context=None):
740         if values and field_name:
741             self._field_get2(cr, uid, obj, context)
742             relation = obj._name
743             res = {}
744             if type(ids) != type([]):
745                 ids=[ids]
746             objlst = obj.browse(cr, uid, ids)
747             for data in objlst:
748                 t_id=None
749                 t_data = data
750                 relation = obj._name
751                 for i in range(len(self.arg)):
752                     field_detail = self._relations[i]
753                     relation = field_detail['object']
754                     if not t_data[self.arg[i]]:
755                         if self._type not in ('one2many', 'many2many'):
756                             t_id = t_data['id']
757                         t_data = False
758                         break
759                     if field_detail['type'] in ('one2many', 'many2many'):
760                         if self._type != "many2one":
761                             t_id = t_data.id
762                             t_data = t_data[self.arg[i]][0]
763                         else:
764                             t_data = False
765                             break
766                     else:
767                         t_id = t_data['id']
768                         t_data = t_data[self.arg[i]]
769
770                 if t_id and t_data:
771                     obj.pool.get(field_detail['object']).write(cr,uid,[t_id],{args[-1]:values}, context=context)
772
773     def _fnct_read(self, obj, cr, uid, ids, field_name, args, context=None):
774         self._field_get2(cr, uid, obj, context)
775         if not ids: return {}
776         relation = obj._name
777         res = {}.fromkeys(ids, False)
778
779         objlst = obj.browse(cr, uid, ids, context=context)
780         for data in objlst:
781             if not data:
782                 continue
783             t_data = data
784             relation = obj._name
785             for i in range(len(self.arg)):
786                 field_detail = self._relations[i]
787                 relation = field_detail['object']
788                 try:
789                     if not t_data[self.arg[i]]:
790                         t_data = False
791                         break
792                 except:
793                     t_data = False
794                     break
795                 if field_detail['type'] in ('one2many', 'many2many') and i != len(self.arg) - 1:
796                     t_data = t_data[self.arg[i]][0]
797                 else:
798                     t_data = t_data[self.arg[i]]
799             if type(t_data) == type(objlst[0]):
800                 res[data.id] = t_data.id
801             else:
802                 res[data.id] = t_data
803         if self._type=='many2one':
804             ids = filter(None, res.values())
805             if ids:
806                 ng = dict(obj.pool.get(self._obj).name_get(cr, uid, ids, context=context))
807                 for r in res:
808                     if res[r]:
809                         res[r] = (res[r], ng[res[r]])
810         elif self._type in ('one2many', 'many2many'):
811             for r in res:
812                 if res[r]:
813                     res[r] = [x.id for x in res[r]]
814         return res
815
816     def __init__(self, *arg, **args):
817         self.arg = arg
818         self._relations = []
819         super(related, self).__init__(self._fnct_read, arg, self._fnct_write, fnct_inv_arg=arg, method=True, fnct_search=self._fnct_search, **args)
820         if self.store is True:
821             # TODO: improve here to change self.store = {...} according to related objects
822             pass
823
824     def _field_get2(self, cr, uid, obj, context={}):
825         if self._relations:
826             return
827         obj_name = obj._name
828         for i in range(len(self._arg)):
829             f = obj.pool.get(obj_name).fields_get(cr, uid, [self._arg[i]], context=context)[self._arg[i]]
830             self._relations.append({
831                 'object': obj_name,
832                 'type': f['type']
833
834             })
835             if f.get('relation',False):
836                 obj_name = f['relation']
837                 self._relations[-1]['relation'] = f['relation']
838
839 # ---------------------------------------------------------
840 # Dummy fields
841 # ---------------------------------------------------------
842
843 class dummy(function):
844     def _fnct_search(self, tobj, cr, uid, obj=None, name=None, domain=None, context={}):
845         return []
846
847     def _fnct_write(self,obj,cr, uid, ids, field_name, values, args, context=None):
848         return False
849
850     def _fnct_read(self, obj, cr, uid, ids, field_name, args, context=None):
851         return {}
852
853     def __init__(self, *arg, **args):
854         self.arg = arg
855         self._relations = []
856         super(dummy, self).__init__(self._fnct_read, arg, self._fnct_write, fnct_inv_arg=arg, method=True, fnct_search=None, **args)
857
858 # ---------------------------------------------------------
859 # Serialized fields
860 # ---------------------------------------------------------
861 class serialized(_column):
862     def __init__(self, string='unknown', serialize_func=repr, deserialize_func=eval, type='text', **args):
863         self._serialize_func = serialize_func
864         self._deserialize_func = deserialize_func
865         self._type = type
866         self._symbol_set = (self._symbol_c, self._serialize_func)
867         self._symbol_get = self._deserialize_func
868         super(serialized, self).__init__(string=string, **args)
869
870
871 class property(function):
872
873     def _fnct_write(self, obj, cr, uid, id, prop, id_val, val, context=None):
874         if not context:
875             context = {}
876         (obj_dest,) = val
877         definition_id = self._field_get(cr, uid, obj._name, prop)
878
879         property = obj.pool.get('ir.property')
880         nid = property.search(cr, uid, [('fields_id', '=', definition_id),
881             ('res_id', '=', obj._name+','+str(id))])
882         while len(nid):
883             cr.execute('DELETE FROM ir_property WHERE id=%s', (nid.pop(),))
884
885         nid = property.search(cr, uid, [('fields_id', '=', definition_id),
886             ('res_id', '=', False)])
887         default_val = False
888         if nid:
889             default_val = property.browse(cr, uid, nid[0], context).value
890
891         company_id = obj.pool.get('res.company')._company_default_get(cr, uid, obj._name, prop, context=context)
892         res = False
893         if val[0]:
894             newval = (id_val and obj_dest+','+str(id_val)) or False
895         else:
896             newval = id_val or False
897         if (newval != default_val) and newval:
898             propdef = obj.pool.get('ir.model.fields').browse(cr, uid,
899                     definition_id, context=context)
900             res = property.create(cr, uid, {
901                 'name': propdef.name,
902                 'value': newval,
903                 'res_id': obj._name+','+str(id),
904                 'company_id': company_id,
905                 'fields_id': definition_id
906             }, context=context)
907         return res
908
909     def _fnct_read(self, obj, cr, uid, ids, prop, val, context=None):
910         if not context:
911             context = {}
912         property = obj.pool.get('ir.property')
913         definition_id = self._field_get(cr, uid, obj._name, prop)
914
915         nid = property.search(cr, uid, [('fields_id', '=', definition_id),
916             ('res_id', '=', False)])
917         default_val = False
918         if nid:
919             d = property.browse(cr, uid, nid[0], context).value
920             default_val = (d and int(d.split(',')[1])) or False
921
922         vids = [obj._name + ',' + str(id) for id in  ids]
923         nids = property.search(cr, uid, [('fields_id', '=', definition_id),
924             ('res_id', 'in', vids)])
925
926         res = {}
927         for id in ids:
928             res[id] = default_val
929         for prop in property.browse(cr, uid, nids):
930             if prop.value.find(',') >= 0:
931                 res[int(prop.res_id.id)] = (prop.value and \
932                         int(prop.value.split(',')[1])) or False
933             else:
934                 res[int(prop.res_id.id)] = prop.value or ''
935
936         if self._obj:
937             obj = obj.pool.get(self._obj)
938             to_check = res.values()
939             if default_val and default_val not in to_check:
940                 to_check += [default_val]
941             existing_ids = obj.search(cr, uid, [('id', 'in', to_check)])
942             for id, res_id in res.items():
943                 if res_id not in existing_ids:
944                     cr.execute('DELETE FROM ir_property WHERE value=%s', ((obj._name+','+str(res_id)),))
945                     res[id] = default_val
946             names = dict(obj.name_get(cr, uid, existing_ids, context))
947             for r in res.keys():
948                 if res[r] and res[r] in names:
949                     res[r] = (res[r], names[res[r]])
950                 else:
951                     res[r] = False
952         return res
953
954     def _field_get(self, cr, uid, model_name, prop):
955         if not self.field_id.get(cr.dbname):
956             cr.execute('SELECT id \
957                     FROM ir_model_fields \
958                     WHERE name=%s AND model=%s', (prop, model_name))
959             res = cr.fetchone()
960             self.field_id[cr.dbname] = res and res[0]
961         return self.field_id[cr.dbname]
962
963     def __init__(self, obj_prop, **args):
964         self.field_id = {}
965         function.__init__(self, self._fnct_read, False, self._fnct_write,
966                 (obj_prop, ), **args)
967
968     def restart(self):
969         self.field_id = {}
970
971
972 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
973