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