fixed bug on relate field
[odoo/odoo.git] / bin / osv / fields.py
1 # -*- encoding: utf-8 -*-
2 ##############################################################################
3 #
4 # Copyright (c) 2004-2008 TINY SPRL. (http://tiny.be) All Rights Reserved.
5 #
6 # $Id$
7 #
8 # WARNING: This program as such is intended to be used by professional
9 # programmers who take the whole responsability of assessing all potential
10 # consequences resulting from its eventual inadequacies and bugs
11 # End users who are looking for a ready-to-use solution with commercial
12 # garantees and support are strongly adviced to contract a Free Software
13 # Service Company
14 #
15 # This program is Free Software; you can redistribute it and/or
16 # modify it under the terms of the GNU General Public License
17 # as published by the Free Software Foundation; either version 2
18 # of the License, or (at your option) any later version.
19 #
20 # This program is distributed in the hope that it will be useful,
21 # but WITHOUT ANY WARRANTY; without even the implied warranty of
22 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
23 # GNU General Public License for more details.
24 #
25 # You should have received a copy of the GNU General Public License
26 # along with this program; if not, write to the Free Software
27 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
28 #
29 ##############################################################################
30
31 # . Fields:
32 #      - simple
33 #      - relations (one2many, many2one, many2many)
34 #      - function
35 #
36 # Fields Attributes:
37 #   _classic_read: is a classic sql fields
38 #   _type   : field type
39 #   readonly
40 #   required
41 #   size
42 #
43 import string
44 import netsvc
45
46 import psycopg
47 import warnings
48
49 import tools
50
51
52 def _symbol_set(symb):
53     if symb == None or symb == False:
54         return None
55     elif isinstance(symb, unicode):
56         return symb.encode('utf-8')
57     return str(symb)
58
59
60 class _column(object):
61     _classic_read = True
62     _classic_write = True
63     _properties = False
64     _type = 'unknown'
65     _obj = None
66     _multi = False
67     _symbol_c = '%s'
68     _symbol_f = _symbol_set
69     _symbol_set = (_symbol_c, _symbol_f)
70     _symbol_get = None
71
72     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):
73         self.states = states or {}
74         self.string = string
75         self.readonly = readonly
76         self.required = required
77         self.size = size
78         self.help = args.get('help', '')
79         self.priority = priority
80         self.change_default = change_default
81         self.ondelete = ondelete
82         self.translate = translate
83         self._domain = domain or []
84         self.relate = False
85         self._context = context
86         self.write = False
87         self.read = False
88         self.view_load = 0
89         self.select = select
90         for a in args:
91             if args[a]:
92                 setattr(self, a, args[a])
93         if self.relate:
94             warnings.warn("The relate attribute doesn't work anymore, use act_window tag instead", DeprecationWarning)
95
96     def restart(self):
97         pass
98
99     def set(self, cr, obj, id, name, value, user=None, context=None):
100         cr.execute('update '+obj._table+' set '+name+'='+self._symbol_set[0]+' where id=%d', (self._symbol_set[1](value), id))
101
102     def set_memory(self, cr, obj, id, name, value, user=None, context=None):
103         raise Exception(_('Not implemented set_memory method !'))
104
105     def get_memory(self, cr, obj, ids, name, user=None, context=None, values=None):
106         raise Exception(_('Not implemented get_memory method !'))
107
108     def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
109         raise Exception(_('undefined get method !'))
110
111     def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None):
112         ids = obj.search(cr, uid, args+self._domain+[(name, 'ilike', value)], offset, limit)
113         res = obj.read(cr, uid, ids, [name])
114         return [x[name] for x in res]
115
116     def search_memory(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, context=None):
117         raise Exception(_('Not implemented search_memory method !'))
118
119
120 # ---------------------------------------------------------
121 # Simple fields
122 # ---------------------------------------------------------
123 class boolean(_column):
124     _type = 'boolean'
125     _symbol_c = '%s'
126     _symbol_f = lambda x: x and 'True' or 'False'
127     _symbol_set = (_symbol_c, _symbol_f)
128
129
130 class integer(_column):
131     _type = 'integer'
132     _symbol_c = '%d'
133     _symbol_f = lambda x: int(x or 0)
134     _symbol_set = (_symbol_c, _symbol_f)
135
136
137 class reference(_column):
138     _type = 'reference'
139
140     def __init__(self, string, selection, size, **args):
141         _column.__init__(self, string=string, size=size, selection=selection, **args)
142
143
144 class char(_column):
145     _type = 'char'
146
147     def __init__(self, string, size, **args):
148         _column.__init__(self, string=string, size=size, **args)
149         self._symbol_set = (self._symbol_c, self._symbol_set_char)
150
151     # takes a string (encoded in utf8) and returns a string (encoded in utf8)
152     def _symbol_set_char(self, symb):
153         #TODO:
154         # * we need to remove the "symb==False" from the next line BUT
155         #   for now too many things rely on this broken behavior
156         # * the symb==None test should be common to all data types
157         if symb == None or symb == False:
158             return None
159
160         # we need to convert the string to a unicode object to be able
161         # to evaluate its length (and possibly truncate it) reliably
162         if isinstance(symb, str):
163             u_symb = unicode(symb, 'utf8')
164         elif isinstance(symb, unicode):
165             u_symb = symb
166         else:
167             u_symb = unicode(symb)
168         return u_symb.encode('utf8')[:self.size]
169
170
171 class text(_column):
172     _type = 'text'
173
174 import __builtin__
175
176
177 class float(_column):
178     _type = 'float'
179     _symbol_c = '%f'
180     _symbol_f = lambda x: __builtin__.float(x or 0.0)
181     _symbol_set = (_symbol_c, _symbol_f)
182
183     def __init__(self, string='unknown', digits=None, **args):
184         _column.__init__(self, string=string, **args)
185         self.digits = digits
186
187
188 class date(_column):
189     _type = 'date'
190
191
192 class datetime(_column):
193     _type = 'datetime'
194
195
196 class time(_column):
197     _type = 'time'
198
199
200 class binary(_column):
201     _type = 'binary'
202     _symbol_c = '%s'
203     _symbol_f = lambda symb: symb and psycopg.Binary(symb) or None
204     _symbol_set = (_symbol_c, _symbol_f)
205
206     _classic_read = False
207
208     def __init__(self, string='unknown', filters=None, **args):
209         _column.__init__(self, string=string, **args)
210         self.filters = filters
211
212     def get_memory(self, cr, obj, ids, name, user=None, context=None, values=None):
213         if not context:
214             context = {}
215         if not values:
216             values = []
217
218         res = {}
219         for i in ids:
220             val = None
221             for v in values:
222                 if v['id'] == i:
223                     val = v[name]
224                     break
225             res.setdefault(i, val)
226             if context.get('get_binary_size', True):
227                 res[i] = tools.human_size(val)
228
229         return res
230
231     get = get_memory
232
233 class selection(_column):
234     _type = 'selection'
235
236     def __init__(self, selection, string='unknown', **args):
237         _column.__init__(self, string=string, **args)
238         self.selection = selection
239
240 # ---------------------------------------------------------
241 # Relationals fields
242 # ---------------------------------------------------------
243
244 #
245 # Values: (0, 0,  { fields })    create
246 #         (1, ID, { fields })    modification
247 #         (2, ID)                remove (delete)
248 #         (3, ID)                unlink one (target id or target of relation)
249 #         (4, ID)                link
250 #         (5)                    unlink all (only valid for one2many)
251 #
252 #CHECKME: dans la pratique c'est quoi la syntaxe utilisee pour le 5? (5) ou (5, 0)?
253 class one2one(_column):
254     _classic_read = False
255     _classic_write = True
256     _type = 'one2one'
257
258     def __init__(self, obj, string='unknown', **args):
259         warnings.warn("The one2one field doesn't work anymore", DeprecationWarning)
260         _column.__init__(self, string=string, **args)
261         self._obj = obj
262
263     def set(self, cr, obj_src, id, field, act, user=None, context=None):
264         if not context:
265             context = {}
266         obj = obj_src.pool.get(self._obj)
267         self._table = obj_src.pool.get(self._obj)._table
268         if act[0] == 0:
269             id_new = obj.create(cr, user, act[1])
270             cr.execute('update '+obj_src._table+' set '+field+'=%d where id=%d', (id_new, id))
271         else:
272             cr.execute('select '+field+' from '+obj_src._table+' where id=%d', (act[0],))
273             id = cr.fetchone()[0]
274             obj.write(cr, user, [id], act[1], context=context)
275
276     def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None):
277         return obj.pool.get(self._obj).search(cr, uid, args+self._domain+[('name', 'like', value)], offset, limit)
278
279
280 class many2one(_column):
281     _classic_read = False
282     _classic_write = True
283     _type = 'many2one'
284
285     def __init__(self, obj, string='unknown', **args):
286         _column.__init__(self, string=string, **args)
287         self._obj = obj
288
289     #
290     # TODO: speed improvement
291     #
292     # name is the name of the relation field
293     def get_memory(self, cr, obj, ids, name, user=None, context=None, values=None):
294         result = {}
295         for id in ids:
296             result[id] = obj.datas[id][name]
297         return result
298
299     def get(self, cr, obj, ids, name, user=None, context=None, values=None):
300         if not context:
301             context = {}
302         if not values:
303             values = {}
304         res = {}
305         for r in values:
306             res[r['id']] = r[name]
307         for id in ids:
308             res.setdefault(id, '')
309         obj = obj.pool.get(self._obj)
310         # build a dictionary of the form {'id_of_distant_resource': name_of_distant_resource}
311         from orm import except_orm
312         try:
313             names = dict(obj.name_get(cr, user, filter(None, res.values()), context))
314         except except_orm:
315             names = {}
316
317             iids = filter(None, res.values())
318             cr.execute('select id,'+obj._rec_name+' from '+obj._table+' where id in ('+','.join(map(str, iids))+')')
319             for res22 in cr.fetchall():
320                 names[res22[0]] = res22[1]
321
322         for r in res.keys():
323             if res[r] and res[r] in names:
324                 res[r] = (res[r], names[res[r]])
325             else:
326                 res[r] = False
327         return res
328
329     def set(self, cr, obj_src, id, field, values, user=None, context=None):
330         if not context:
331             context = {}
332         obj = obj_src.pool.get(self._obj)
333         self._table = obj_src.pool.get(self._obj)._table
334         if type(values)==type([]):
335             for act in values:
336                 if act[0] == 0:
337                     id_new = obj.create(cr, act[2])
338                     cr.execute('update '+obj_src._table+' set '+field+'=%d where id=%d', (id_new, id))
339                 elif act[0] == 1:
340                     obj.write(cr, [act[1]], act[2], context=context)
341                 elif act[0] == 2:
342                     cr.execute('delete from '+self._table+' where id=%d', (act[1],))
343                 elif act[0] == 3 or act[0] == 5:
344                     cr.execute('update '+obj_src._table+' set '+field+'=null where id=%d', (id,))
345                 elif act[0] == 4:
346                     cr.execute('update '+obj_src._table+' set '+field+'=%d where id=%d', (act[1], id))
347         else:
348             if values:
349                 cr.execute('update '+obj_src._table+' set '+field+'=%d where id=%d', (values, id))
350             else:
351                 cr.execute('update '+obj_src._table+' set '+field+'=null where id=%d', (id,))
352
353     def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None):
354         return obj.pool.get(self._obj).search(cr, uid, args+self._domain+[('name', 'like', value)], offset, limit)
355
356
357 class one2many(_column):
358     _classic_read = False
359     _classic_write = False
360     _type = 'one2many'
361
362     def __init__(self, obj, fields_id, string='unknown', limit=None, **args):
363         _column.__init__(self, string=string, **args)
364         self._obj = obj
365         self._fields_id = fields_id
366         self._limit = limit
367         #one2many can't be used as condition for defaults
368         assert(self.change_default != True)
369
370     def get_memory(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
371         if not context:
372             context = {}
373         if not values:
374             values = {}
375         res = {}
376         for id in ids:
377             res[id] = []
378         ids2 = obj.pool.get(self._obj).search(cr, user, [(self._fields_id, 'in', ids)], limit=self._limit)
379         for r in obj.pool.get(self._obj).read(cr, user, ids2, [self._fields_id], context=context, load='_classic_write'):
380             if r[self._fields_id] in res:
381                 res[r[self._fields_id]].append(r['id'])
382         return res
383
384     def set_memory(self, cr, obj, id, field, values, user=None, context=None):
385         if not context:
386             context = {}
387         if not values:
388             return
389         obj = obj.pool.get(self._obj)
390         for act in values:
391             if act[0] == 0:
392                 act[2][self._fields_id] = id
393                 obj.create(cr, user, act[2], context=context)
394             elif act[0] == 1:
395                 obj.write(cr, user, [act[1]], act[2], context=context)
396             elif act[0] == 2:
397                 obj.unlink(cr, user, [act[1]], context=context)
398             elif act[0] == 3:
399                 obj.datas[act[1]][self._fields_id] = False
400             elif act[0] == 4:
401                 obj.datas[act[1]] = id
402             elif act[0] == 5:
403                 for o in obj.datas.values():
404                     if o[self._fields_id] == id:
405                         o[self._fields_id] = False
406             elif act[0] == 6:
407                 for id2 in (act[2] or []):
408                     obj.datas[id2][self._fields_id] = id
409
410     def search_memory(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, operator='like', context=None):
411         raise _('Not Implemented')
412
413     def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
414         if not context:
415             context = {}
416         if not values:
417             values = {}
418         res = {}
419         for id in ids:
420             res[id] = []
421         ids2 = obj.pool.get(self._obj).search(cr, user, [(self._fields_id, 'in', ids)], limit=self._limit)
422         for r in obj.pool.get(self._obj)._read_flat(cr, user, ids2, [self._fields_id], context=context, load='_classic_write'):
423             res[r[self._fields_id]].append(r['id'])
424         return res
425
426     def set(self, cr, obj, id, field, values, user=None, context=None):
427         if not context:
428             context = {}
429         if not values:
430             return
431         _table = obj.pool.get(self._obj)._table
432         obj = obj.pool.get(self._obj)
433         for act in values:
434             if act[0] == 0:
435                 act[2][self._fields_id] = id
436                 obj.create(cr, user, act[2], context=context)
437             elif act[0] == 1:
438                 obj.write(cr, user, [act[1]], act[2], context=context)
439             elif act[0] == 2:
440                 obj.unlink(cr, user, [act[1]], context=context)
441             elif act[0] == 3:
442                 cr.execute('update '+_table+' set '+self._fields_id+'=null where id=%d', (act[1],))
443             elif act[0] == 4:
444                 cr.execute('update '+_table+' set '+self._fields_id+'=%d where id=%d', (id, act[1]))
445             elif act[0] == 5:
446                 cr.execute('update '+_table+' set '+self._fields_id+'=null where '+self._fields_id+'=%d', (id,))
447             elif act[0] == 6:
448                 if not act[2]:
449                     ids2 = [0]
450                 else:
451                     ids2 = act[2]
452                 cr.execute('update '+_table+' set '+self._fields_id+'=NULL where '+self._fields_id+'=%d and id not in ('+','.join(map(str, ids2))+')', (id,))
453                 if act[2]:
454                     cr.execute('update '+_table+' set '+self._fields_id+'=%d where id in ('+','.join(map(str, act[2]))+')', (id,))
455
456     def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, operator='like'):
457         return obj.pool.get(self._obj).name_search(cr, uid, value, self._domain, offset, limit)
458
459
460 #
461 # Values: (0, 0,  { fields })    create
462 #         (1, ID, { fields })    modification
463 #         (2, ID)                remove
464 #         (3, ID)                unlink
465 #         (4, ID)                link
466 #         (5, ID)                unlink all
467 #         (6, ?, ids)            set a list of links
468 #
469 class many2many(_column):
470     _classic_read = False
471     _classic_write = False
472     _type = 'many2many'
473
474     def __init__(self, obj, rel, id1, id2, string='unknown', limit=None, **args):
475         _column.__init__(self, string=string, **args)
476         self._obj = obj
477         self._rel = rel
478         self._id1 = id1
479         self._id2 = id2
480         self._limit = limit
481
482     def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
483         if not context:
484             context = {}
485         if not values:
486             values = {}
487         res = {}
488         if not ids:
489             return res
490         for id in ids:
491             res[id] = []
492         ids_s = ','.join(map(str, ids))
493         limit_str = self._limit is not None and ' limit %d' % self._limit or ''
494         obj = obj.pool.get(self._obj)
495
496         d1, d2 = obj.pool.get('ir.rule').domain_get(cr, user, obj._name)
497         if d1:
498             d1 = ' and '+d1
499
500         cr.execute('SELECT '+self._rel+'.'+self._id2+','+self._rel+'.'+self._id1+' \
501                 FROM '+self._rel+' , '+obj._table+' \
502                 WHERE '+self._rel+'.'+self._id1+' in ('+ids_s+') \
503                     AND '+self._rel+'.'+self._id2+' = '+obj._table+'.id '+d1
504                 +limit_str+' order by '+obj._table+'.'+obj._order+' offset %d',
505                 d2+[offset])
506         for r in cr.fetchall():
507             res[r[1]].append(r[0])
508         return res
509
510     def set(self, cr, obj, id, name, values, user=None, context=None):
511         if not context:
512             context = {}
513         if not values:
514             return
515         obj = obj.pool.get(self._obj)
516         for act in values:
517             if act[0] == 0:
518                 idnew = obj.create(cr, user, act[2])
519                 cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%d,%d)', (id, idnew))
520             elif act[0] == 1:
521                 obj.write(cr, user, [act[1]], act[2], context=context)
522             elif act[0] == 2:
523                 obj.unlink(cr, user, [act[1]], context=context)
524             elif act[0] == 3:
525                 cr.execute('delete from '+self._rel+' where ' + self._id1 + '=%d and '+ self._id2 + '=%d', (id, act[1]))
526             elif act[0] == 4:
527                 cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%d,%d)', (id, act[1]))
528             elif act[0] == 5:
529                 cr.execute('update '+self._rel+' set '+self._id2+'=null where '+self._id2+'=%d', (id,))
530             elif act[0] == 6:
531
532                 d1, d2 = obj.pool.get('ir.rule').domain_get(cr, user, obj._name)
533                 if d1:
534                     d1 = ' and '+d1
535                 cr.execute('delete from '+self._rel+' where '+self._id1+'=%d AND '+self._id2+' IN (SELECT '+self._rel+'.'+self._id2+' FROM '+self._rel+', '+obj._table+' WHERE '+self._rel+'.'+self._id1+'=%d AND '+self._rel+'.'+self._id2+' = '+obj._table+'.id '+ d1 +')', [id, id]+d2)
536
537                 for act_nbr in act[2]:
538                     cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%d, %d)', (id, act_nbr))
539
540     #
541     # TODO: use a name_search
542     #
543     def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, operator='like'):
544         return obj.pool.get(self._obj).search(cr, uid, args+self._domain+[('name', operator, value)], offset, limit)
545
546     def get_memory(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
547         result = {}
548         for id in ids:
549             result[id] = obj.datas[id].get(name, [])
550         return result
551
552     def set_memory(self, cr, obj, id, name, values, user=None, context=None):
553         if not values:
554             return
555         for act in values:
556             # TODO: use constants instead of these magic numbers
557             if act[0] == 0:
558                 raise _('Not Implemented')
559             elif act[0] == 1:
560                 raise _('Not Implemented')
561             elif act[0] == 2:
562                 raise _('Not Implemented')
563             elif act[0] == 3:
564                 raise _('Not Implemented')
565             elif act[0] == 4:
566                 raise _('Not Implemented')
567             elif act[0] == 5:
568                 raise _('Not Implemented')
569             elif act[0] == 6:
570                 obj.datas[id][name] = act[2]
571
572
573 # ---------------------------------------------------------
574 # Function fields
575 # ---------------------------------------------------------
576 class function(_column):
577     _classic_read = False
578     _classic_write = False
579     _type = 'function'
580     _properties = True
581
582 #
583 # multi: compute several fields in one call
584 #
585     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):
586         _column.__init__(self, **args)
587         self._obj = obj
588         self._method = method
589         self._fnct = fnct
590         self._fnct_inv = fnct_inv
591         self._arg = arg
592         self._multi = multi
593         if 'relation' in args:
594             self._obj = args['relation']
595         self._fnct_inv_arg = fnct_inv_arg
596         if not fnct_inv:
597             self.readonly = 1
598         self._type = type
599         self._fnct_search = fnct_search
600         self.store = store
601         if type == 'float':
602             self._symbol_c = '%f'
603             self._symbol_f = lambda x: __builtin__.float(x or 0.0)
604             self._symbol_set = (self._symbol_c, self._symbol_f)
605
606     def search(self, cr, uid, obj, name, args):
607         if not self._fnct_search:
608             #CHECKME: should raise an exception
609             return []
610         return self._fnct_search(obj, cr, uid, obj, name, args)
611
612     def get(self, cr, obj, ids, name, user=None, context=None, values=None):
613         if not context:
614             context = {}
615         if not values:
616             values = {}
617         res = {}
618         if self._method:
619             res = self._fnct(obj, cr, user, ids, name, self._arg, context)
620         else:
621             res = self._fnct(cr, obj._table, ids, name, self._arg, context)
622
623         if self._type == 'binary' and context.get('get_binary_size', True):
624             # convert the data returned by the function with the size of that data...
625             res = dict(map(lambda (x, y): (x, tools.human_size(len(y))), res.items()))
626         return res
627
628     def set(self, cr, obj, id, name, value, user=None, context=None):
629         if not context:
630             context = {}
631         if self._fnct_inv:
632             self._fnct_inv(obj, cr, user, id, name, value, self._fnct_inv_arg, context)
633
634 # ---------------------------------------------------------
635 # Related fields
636 # ---------------------------------------------------------
637
638 class related(function):
639
640     def _fnct_search(self, cr, uid, ids, obj=None, name=None, context=None):
641         print "_fnct_search >>>",ids,obj,name
642         return self._fnct_search(obj, cr, uid, obj, name, args)
643
644     def _fnct_read(self,obj,cr, uid, ids, field_name, args, context=None):
645         relation=obj._name
646         res={}
647         for data in obj.browse(cr,uid,ids):
648             t_data=data
649             relation=obj._name
650             for i in range(0,len(args)-1):
651                 field_detail=self._field_get(cr,uid,relation,args[i])
652                 relation=field_detail[0]
653                 if field_detail[1]=='one2many':
654                     if t_data[args[i]]:
655                         t_data=t_data[args[i]][0]
656                     else:
657                         t_data=False
658                         break
659                 elif field_detail[1]=='many2one':
660                     if t_data[args[i]]:
661                         t_data=t_data[args[i]]
662                     else:
663                         t_data=False
664                         break
665             if t_data:
666                 res[data.id]=t_data[args[len(args)-1]]
667             else:
668                 res[data.id]=t_data
669         return res
670     
671     def __init__(self,*arg,**args):
672         function.__init__(self,self._fnct_read, arg, fnct_inv_arg=arg,method=True, fnct_search=self._fnct_search,**args)
673
674     def _field_get(self, cr, uid, model_name, prop):
675         cr.execute('SELECT relation,ttype FROM ir_model_fields WHERE name=%s AND model=%s', (prop, model_name))
676         res = cr.fetchone()
677         return res
678
679 # ---------------------------------------------------------
680 # Serialized fields
681 # ---------------------------------------------------------
682 class serialized(_column):
683     def __init__(self, string='unknown', serialize_func=repr, deserialize_func=eval, type='text', **args):
684         self._serialize_func = serialize_func
685         self._deserialize_func = deserialize_func
686         self._type = type
687         self._symbol_set = (self._symbol_c, self._serialize_func)
688         self._symbol_get = self._deserialize_func
689         super(serialized, self).__init__(string=string, **args)
690
691
692 class property(function):
693
694     def _fnct_write(self, obj, cr, uid, id, prop, id_val, val, context=None):
695         if not context:
696             context = {}
697         (obj_dest,) = val
698         definition_id = self._field_get(cr, uid, obj._name, prop)
699
700         property = obj.pool.get('ir.property')
701         nid = property.search(cr, uid, [('fields_id', '=', definition_id),
702             ('res_id', '=', obj._name+','+str(id))])
703         while len(nid):
704             cr.execute('DELETE FROM ir_property WHERE id=%d', (nid.pop(),))
705
706         nid = property.search(cr, uid, [('fields_id', '=', definition_id),
707             ('res_id', '=', False)])
708         default_val = False
709         if nid:
710             default_val = property.browse(cr, uid, nid[0], context).value
711
712         company_id = obj.pool.get('res.users').company_get(cr, uid, uid)
713         res = False
714         newval = (id_val and obj_dest+','+str(id_val)) or False
715         if (newval != default_val) and newval:
716             propdef = obj.pool.get('ir.model.fields').browse(cr, uid,
717                     definition_id, context=context)
718             res = property.create(cr, uid, {
719                 'name': propdef.name,
720                 'value': newval,
721                 'res_id': obj._name+','+str(id),
722                 'company_id': company_id,
723                 'fields_id': definition_id
724             }, context=context)
725         return res
726
727     def _fnct_read(self, obj, cr, uid, ids, prop, val, context=None):
728         if not context:
729             context = {}
730         property = obj.pool.get('ir.property')
731         definition_id = self._field_get(cr, uid, obj._name, prop)
732
733         nid = property.search(cr, uid, [('fields_id', '=', definition_id),
734             ('res_id', '=', False)])
735         default_val = False
736         if nid:
737             d = property.browse(cr, uid, nid[0], context).value
738             default_val = (d and int(d.split(',')[1])) or False
739
740         vids = [obj._name + ',' + str(id) for id in  ids]
741         nids = property.search(cr, uid, [('fields_id', '=', definition_id),
742             ('res_id', 'in', vids)])
743
744         res = {}
745         for id in ids:
746             res[id] = default_val
747         for prop in property.browse(cr, uid, nids):
748             res[int(prop.res_id.split(',')[1])] = (prop.value and \
749                     int(prop.value.split(',')[1])) or False
750
751         obj = obj.pool.get(self._obj)
752         names = dict(obj.name_get(cr, uid, filter(None, res.values()), context))
753         for r in res.keys():
754             if res[r] and res[r] in names:
755                 res[r] = (res[r], names[res[r]])
756             else:
757                 res[r] = False
758         return res
759
760     def _field_get(self, cr, uid, model_name, prop):
761         if not self.field_id.get(cr.dbname):
762             cr.execute('SELECT id \
763                     FROM ir_model_fields \
764                     WHERE name=%s AND model=%s', (prop, model_name))
765             res = cr.fetchone()
766             self.field_id[cr.dbname] = res and res[0]
767         return self.field_id[cr.dbname]
768
769     def __init__(self, obj_prop, **args):
770         self.field_id = {}
771         function.__init__(self, self._fnct_read, False, self._fnct_write,
772                 (obj_prop, ), **args)
773
774     def restart(self):
775         self.field_id = {}
776
777
778 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
779