[Merged]
[odoo/odoo.git] / bin / osv / fields.py
1 # -*- encoding: 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 not in ('+','.join(map(str, ids2))+')', (id,))
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         ids_s = ','.join(map(str, ids))
508         limit_str = self._limit is not None and ' limit %d' % self._limit or ''
509         obj = obj.pool.get(self._obj)
510
511         d1, d2 = obj.pool.get('ir.rule').domain_get(cr, user, obj._name)
512         if d1:
513             d1 = ' and ' + d1
514
515         cr.execute('SELECT '+self._rel+'.'+self._id2+','+self._rel+'.'+self._id1+' \
516                 FROM '+self._rel+' , '+obj._table+' \
517                 WHERE '+self._rel+'.'+self._id1+' in ('+ids_s+') \
518                     AND '+self._rel+'.'+self._id2+' = '+obj._table+'.id '+d1
519                 +limit_str+' order by '+obj._table+'.'+obj._order+' offset %s',
520                 d2+[offset])
521         for r in cr.fetchall():
522             res[r[1]].append(r[0])
523         return res
524
525     def set(self, cr, obj, id, name, values, user=None, context=None):
526         if not context:
527             context = {}
528         if not values:
529             return
530         obj = obj.pool.get(self._obj)
531         for act in values:
532             if act[0] == 0:
533                 idnew = obj.create(cr, user, act[2])
534                 cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%s,%s)', (id, idnew))
535             elif act[0] == 1:
536                 obj.write(cr, user, [act[1]], act[2], context=context)
537             elif act[0] == 2:
538                 obj.unlink(cr, user, [act[1]], context=context)
539             elif act[0] == 3:
540                 cr.execute('delete from '+self._rel+' where ' + self._id1 + '=%s and '+ self._id2 + '=%s', (id, act[1]))
541             elif act[0] == 4:
542                 cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%s,%s)', (id, act[1]))
543             elif act[0] == 5:
544                 cr.execute('update '+self._rel+' set '+self._id2+'=null where '+self._id2+'=%s', (id,))
545             elif act[0] == 6:
546
547                 d1, d2 = obj.pool.get('ir.rule').domain_get(cr, user, obj._name)
548                 if d1:
549                     d1 = ' and ' + d1
550                 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)
551
552                 for act_nbr in act[2]:
553                     cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%s, %s)', (id, act_nbr))
554
555     #
556     # TODO: use a name_search
557     #
558     def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, operator='like'):
559         return obj.pool.get(self._obj).search(cr, uid, args+self._domain+[('name', operator, value)], offset, limit)
560
561     def get_memory(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
562         result = {}
563         for id in ids:
564             result[id] = obj.datas[id].get(name, [])
565         return result
566
567     def set_memory(self, cr, obj, id, name, values, user=None, context=None):
568         if not values:
569             return
570         for act in values:
571             # TODO: use constants instead of these magic numbers
572             if act[0] == 0:
573                 raise _('Not Implemented')
574             elif act[0] == 1:
575                 raise _('Not Implemented')
576             elif act[0] == 2:
577                 raise _('Not Implemented')
578             elif act[0] == 3:
579                 raise _('Not Implemented')
580             elif act[0] == 4:
581                 raise _('Not Implemented')
582             elif act[0] == 5:
583                 raise _('Not Implemented')
584             elif act[0] == 6:
585                 obj.datas[id][name] = act[2]
586
587
588 # ---------------------------------------------------------
589 # Function fields
590 # ---------------------------------------------------------
591 class function(_column):
592     _classic_read = False
593     _classic_write = False
594     _prefetch = False
595     _type = 'function'
596     _properties = True
597
598 #
599 # multi: compute several fields in one call
600 #
601     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):
602         _column.__init__(self, **args)
603         self._obj = obj
604         self._method = method
605         self._fnct = fnct
606         self._fnct_inv = fnct_inv
607         self._arg = arg
608         self._multi = multi
609         if 'relation' in args:
610             self._obj = args['relation']
611         self._fnct_inv_arg = fnct_inv_arg
612         if not fnct_inv:
613             self.readonly = 1
614         self._type = type
615         self._fnct_search = fnct_search
616         self.store = store
617
618         if not fnct_search and not store:
619             self.selectable = False
620         
621         if store:
622             self._classic_read = True
623             self._classic_write = True
624             if type=='binary':
625                 self._symbol_get=lambda x:x and str(x)
626
627         if type == 'float':
628             self._symbol_c = float._symbol_c
629             self._symbol_f = float._symbol_f
630             self._symbol_set = float._symbol_set
631
632     def search(self, cr, uid, obj, name, args):
633         if not self._fnct_search:
634             #CHECKME: should raise an exception
635             return []
636         return self._fnct_search(obj, cr, uid, obj, name, args)
637
638     def get(self, cr, obj, ids, name, user=None, context=None, values=None):
639         if not context:
640             context = {}
641         if not values:
642             values = {}
643         res = {}
644         if self._method:
645             res = self._fnct(obj, cr, user, ids, name, self._arg, context)
646         else:
647             res = self._fnct(cr, obj._table, ids, name, self._arg, context)
648
649         if self._type == "many2one" :
650             # Filtering only integer/long values if passed
651             res_ids = [x for x in res.values() if x and isinstance(x, (int,long))]
652             
653             if res_ids:
654                 obj_model = obj.pool.get(self._obj)
655                 dict_names = dict(obj_model.name_get(cr, user, res_ids, context))
656                 for r in res.keys():
657                     if res[r] and res[r] in dict_names:
658                         res[r] = (res[r], dict_names[res[r]])
659             
660         if self._type == 'binary' and context.get('bin_size', False):
661             # convert the data returned by the function with the size of that data...
662             res = dict(map(lambda (x, y): (x, tools.human_size(len(y or ''))), res.items()))
663         return res
664     get_memory = get
665
666     def set(self, cr, obj, id, name, value, user=None, context=None):
667         if not context:
668             context = {}
669         if self._fnct_inv:
670             self._fnct_inv(obj, cr, user, id, name, value, self._fnct_inv_arg, context)
671     set_memory = set
672
673 # ---------------------------------------------------------
674 # Related fields
675 # ---------------------------------------------------------
676
677 class related(function):
678
679     def _fnct_search(self, tobj, cr, uid, obj=None, name=None, domain=None, context={}):
680         self._field_get2(cr, uid, obj, context)
681         i = len(self._arg)-1
682         sarg = name
683         while i>0:
684             if type(sarg) in [type([]), type( (1,) )]:
685                 where = [(self._arg[i], 'in', sarg)]
686             else:
687                 where = [(self._arg[i], '=', sarg)]
688             if domain:
689                 where = map(lambda x: (self._arg[i],x[1], x[2]), domain)
690                 domain = []
691             sarg = obj.pool.get(self._relations[i]['object']).search(cr, uid, where, context=context)
692             i -= 1
693         return [(self._arg[0], 'in', sarg)]
694
695     def _fnct_write(self,obj,cr, uid, ids, field_name, values, args, context=None):
696         if values and field_name:
697             self._field_get2(cr, uid, obj, context)
698             relation = obj._name
699             res = {}
700             if type(ids) != type([]):
701                 ids=[ids]
702             objlst = obj.browse(cr, uid, ids)
703             for data in objlst:
704                 t_id=None
705                 t_data = data
706                 relation = obj._name
707                 for i in range(len(self.arg)):
708                     field_detail = self._relations[i]
709                     relation = field_detail['object']
710                     if not t_data[self.arg[i]]:
711                         t_data = False
712                         break
713                     if field_detail['type'] in ('one2many', 'many2many'):
714                         if self._type != "many2one":
715                             t_id=t_data.id
716                             t_data = t_data[self.arg[i]][0]
717                     else:
718                         t_id=t_data['id']
719                         t_data = t_data[self.arg[i]]
720                 if t_id:
721                     obj.pool.get(field_detail['object']).write(cr,uid,[t_id],{args[-1]:values})
722
723     def _fnct_read(self, obj, cr, uid, ids, field_name, args, context=None):
724         self._field_get2(cr, uid, obj, context)
725         if not ids: return {}
726         relation = obj._name
727         res = {}.fromkeys(ids, False)
728         objlst = obj.browse(cr, uid, ids)
729         for data in objlst:
730             if not data:
731                 continue
732             t_data = data
733             relation = obj._name
734             for i in range(len(self.arg)):
735                 field_detail = self._relations[i]
736                 relation = field_detail['object']
737                 try:
738                     if not t_data[self.arg[i]]:
739                         t_data = False
740                         break
741                 except:
742                     t_data = False
743                     break
744                 if field_detail['type'] in ('one2many', 'many2many'):
745                     t_data = t_data[self.arg[i]][0]
746                 else:
747                     t_data = t_data[self.arg[i]]
748             if type(t_data) == type(objlst[0]):
749                 res[data.id] = t_data.id
750             else:
751                 res[data.id] = t_data
752
753         if self._type=='many2one':
754             ids = filter(None, res.values())
755             if ids:
756                 ng = dict(obj.pool.get(self._obj).name_get(cr, uid, ids, context=context))
757                 for r in res:
758                     if res[r]:
759                         res[r] = (res[r], ng[res[r]])
760         return res
761
762     def __init__(self, *arg, **args):
763         self.arg = arg
764         self._relations = []
765         super(related, self).__init__(self._fnct_read, arg, self._fnct_write, fnct_inv_arg=arg, method=True, fnct_search=self._fnct_search, **args)
766
767     def _field_get2(self, cr, uid, obj, context={}):
768         if self._relations:
769             return
770         obj_name = obj._name
771         for i in range(len(self._arg)):
772             f = obj.pool.get(obj_name).fields_get(cr, uid, [self._arg[i]], context=context)[self._arg[i]]
773             self._relations.append({
774                 'object': obj_name,
775                 'type': f['type']
776
777             })
778             if f.get('relation',False):
779                 obj_name = f['relation']
780                 self._relations[-1]['relation'] = f['relation']
781
782 # ---------------------------------------------------------
783 # Dummy fields
784 # ---------------------------------------------------------
785
786 class dummy(function):
787     def _fnct_search(self, tobj, cr, uid, obj=None, name=None, domain=None, context={}):
788         return []
789
790     def _fnct_write(self,obj,cr, uid, ids, field_name, values, args, context=None):
791         return False
792
793     def _fnct_read(self, obj, cr, uid, ids, field_name, args, context=None):
794         return {}
795     
796     def __init__(self, *arg, **args):
797         self.arg = arg
798         self._relations = []
799         super(dummy, self).__init__(self._fnct_read, arg, self._fnct_write, fnct_inv_arg=arg, method=True, fnct_search=None, **args)
800
801 # ---------------------------------------------------------
802 # Serialized fields
803 # ---------------------------------------------------------
804 class serialized(_column):
805     def __init__(self, string='unknown', serialize_func=repr, deserialize_func=eval, type='text', **args):
806         self._serialize_func = serialize_func
807         self._deserialize_func = deserialize_func
808         self._type = type
809         self._symbol_set = (self._symbol_c, self._serialize_func)
810         self._symbol_get = self._deserialize_func
811         super(serialized, self).__init__(string=string, **args)
812
813
814 class property(function):
815
816     def _fnct_write(self, obj, cr, uid, id, prop, id_val, val, context=None):
817         if not context:
818             context = {}
819         (obj_dest,) = val
820         definition_id = self._field_get(cr, uid, obj._name, prop)
821
822         property = obj.pool.get('ir.property')
823         nid = property.search(cr, uid, [('fields_id', '=', definition_id),
824             ('res_id', '=', obj._name+','+str(id))])
825         while len(nid):
826             cr.execute('DELETE FROM ir_property WHERE id=%s', (nid.pop(),))
827
828         nid = property.search(cr, uid, [('fields_id', '=', definition_id),
829             ('res_id', '=', False)])
830         default_val = False
831         if nid:
832             default_val = property.browse(cr, uid, nid[0], context).value
833
834         company_id = obj.pool.get('res.users').company_get(cr, uid, uid)
835         res = False
836         newval = (id_val and obj_dest+','+str(id_val)) or False
837         if (newval != default_val) and newval:
838             propdef = obj.pool.get('ir.model.fields').browse(cr, uid,
839                     definition_id, context=context)
840             res = property.create(cr, uid, {
841                 'name': propdef.name,
842                 'value': newval,
843                 'res_id': obj._name+','+str(id),
844                 'company_id': company_id,
845                 'fields_id': definition_id
846             }, context=context)
847         return res
848
849     def _fnct_read(self, obj, cr, uid, ids, prop, val, context=None):
850         if not context:
851             context = {}
852         property = obj.pool.get('ir.property')
853         definition_id = self._field_get(cr, uid, obj._name, prop)
854
855         nid = property.search(cr, uid, [('fields_id', '=', definition_id),
856             ('res_id', '=', False)])
857         default_val = False
858         if nid:
859             d = property.browse(cr, uid, nid[0], context).value
860             default_val = (d and int(d.split(',')[1])) or False
861
862         vids = [obj._name + ',' + str(id) for id in  ids]
863         nids = property.search(cr, uid, [('fields_id', '=', definition_id),
864             ('res_id', 'in', vids)])
865
866         res = {}
867         for id in ids:
868             res[id] = default_val
869         for prop in property.browse(cr, uid, nids):
870             res[int(prop.res_id.split(',')[1])] = (prop.value and \
871                     int(prop.value.split(',')[1])) or False
872
873         obj = obj.pool.get(self._obj)
874
875         to_check = res.values()
876         if default_val and default_val not in to_check:
877             to_check += [default_val]
878         existing_ids = obj.search(cr, uid, [('id', 'in', to_check)])
879         
880         for id, res_id in res.items():
881             if res_id not in existing_ids:
882                 cr.execute('DELETE FROM ir_property WHERE value=%s', ((obj._name+','+str(res_id)),))
883                 res[id] = default_val
884
885         names = dict(obj.name_get(cr, uid, existing_ids, context))
886         for r in res.keys():
887             if res[r] and res[r] in names:
888                 res[r] = (res[r], names[res[r]])
889             else:
890                 res[r] = False
891         return res
892
893     def _field_get(self, cr, uid, model_name, prop):
894         if not self.field_id.get(cr.dbname):
895             cr.execute('SELECT id \
896                     FROM ir_model_fields \
897                     WHERE name=%s AND model=%s', (prop, model_name))
898             res = cr.fetchone()
899             self.field_id[cr.dbname] = res and res[0]
900         return self.field_id[cr.dbname]
901
902     def __init__(self, obj_prop, **args):
903         self.field_id = {}
904         function.__init__(self, self._fnct_read, False, self._fnct_write,
905                 (obj_prop, ), **args)
906
907     def restart(self):
908         self.field_id = {}
909
910
911 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
912