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