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