[FIX] psycopg2: %d -> %s
[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 from psycopg2 import Binary
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=%s', (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 = '%s'
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 = '%s'
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[:self.size].encode('utf8')
164
165
166 class text(_column):
167     _type = 'text'
168
169 import __builtin__
170
171 class float(_column):
172     _type = 'float'
173     _symbol_c = '%s'
174     _symbol_f = lambda x: __builtin__.float(x or 0.0)
175     _symbol_set = (_symbol_c, _symbol_f)
176
177     def __init__(self, string='unknown', digits=None, **args):
178         _column.__init__(self, string=string, **args)
179         self.digits = digits
180
181
182 class date(_column):
183     _type = 'date'
184
185
186 class datetime(_column):
187     _type = 'datetime'
188
189
190 class time(_column):
191     _type = 'time'
192
193
194 class binary(_column):
195     _type = 'binary'
196     _symbol_c = '%s'
197     _symbol_f = lambda symb: symb and Binary(symb) or None
198     _symbol_set = (_symbol_c, _symbol_f)
199
200     _classic_read = False
201
202     def __init__(self, string='unknown', filters=None, **args):
203         _column.__init__(self, string=string, **args)
204         self.filters = filters
205
206     def get_memory(self, cr, obj, ids, name, user=None, context=None, values=None):
207         if not context:
208             context = {}
209         if not values:
210             values = []
211
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             res.setdefault(i, val)
220             if context.get('bin_size', False):
221                 res[i] = tools.human_size(val)
222
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
280     def __init__(self, obj, string='unknown', **args):
281         _column.__init__(self, string=string, **args)
282         self._obj = obj
283
284     #
285     # TODO: speed improvement
286     #
287     # name is the name of the relation field
288     def get_memory(self, cr, obj, ids, name, user=None, context=None, values=None):
289         result = {}
290         for id in ids:
291             result[id] = obj.datas[id][name]
292         return result
293
294     def get(self, cr, obj, ids, name, user=None, context=None, values=None):
295         if not context:
296             context = {}
297         if not values:
298             values = {}
299         res = {}
300         for r in values:
301             res[r['id']] = r[name]
302         for id in ids:
303             res.setdefault(id, '')
304         obj = obj.pool.get(self._obj)
305         # build a dictionary of the form {'id_of_distant_resource': name_of_distant_resource}
306         from orm import except_orm
307         try:
308             names = dict(obj.name_get(cr, user, filter(None, res.values()), context))
309         except except_orm:
310             names = {}
311
312             iids = filter(None, res.values())
313             cr.execute('select id,'+obj._rec_name+' from '+obj._table+' where id in ('+','.join(map(str, iids))+')')
314             for res22 in cr.fetchall():
315                 names[res22[0]] = res22[1]
316
317         for r in res.keys():
318             if res[r] and res[r] in names:
319                 res[r] = (res[r], names[res[r]])
320             else:
321                 res[r] = False
322         return res
323
324     def set(self, cr, obj_src, id, field, values, user=None, context=None):
325         if not context:
326             context = {}
327         obj = obj_src.pool.get(self._obj)
328         self._table = obj_src.pool.get(self._obj)._table
329         if type(values) == type([]):
330             for act in values:
331                 if act[0] == 0:
332                     id_new = obj.create(cr, act[2])
333                     cr.execute('update '+obj_src._table+' set '+field+'=%s where id=%s', (id_new, id))
334                 elif act[0] == 1:
335                     obj.write(cr, [act[1]], act[2], context=context)
336                 elif act[0] == 2:
337                     cr.execute('delete from '+self._table+' where id=%s', (act[1],))
338                 elif act[0] == 3 or act[0] == 5:
339                     cr.execute('update '+obj_src._table+' set '+field+'=null where id=%s', (id,))
340                 elif act[0] == 4:
341                     cr.execute('update '+obj_src._table+' set '+field+'=%s where id=%s', (act[1], id))
342         else:
343             if values:
344                 cr.execute('update '+obj_src._table+' set '+field+'=%s where id=%s', (values, id))
345             else:
346                 cr.execute('update '+obj_src._table+' set '+field+'=null where id=%s', (id,))
347
348     def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None):
349         return obj.pool.get(self._obj).search(cr, uid, args+self._domain+[('name', 'like', value)], offset, limit)
350
351
352 class one2many(_column):
353     _classic_read = False
354     _classic_write = False
355     _type = 'one2many'
356
357     def __init__(self, obj, fields_id, string='unknown', limit=None, **args):
358         _column.__init__(self, string=string, **args)
359         self._obj = obj
360         self._fields_id = fields_id
361         self._limit = limit
362         #one2many can't be used as condition for defaults
363         assert(self.change_default != True)
364
365     def get_memory(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
366         if not context:
367             context = {}
368         if not values:
369             values = {}
370         res = {}
371         for id in ids:
372             res[id] = []
373         ids2 = obj.pool.get(self._obj).search(cr, user, [(self._fields_id, 'in', ids)], limit=self._limit)
374         for r in obj.pool.get(self._obj).read(cr, user, ids2, [self._fields_id], context=context, load='_classic_write'):
375             if r[self._fields_id] in res:
376                 res[r[self._fields_id]].append(r['id'])
377         return res
378
379     def set_memory(self, cr, obj, id, field, values, user=None, context=None):
380         if not context:
381             context = {}
382         if not values:
383             return
384         obj = obj.pool.get(self._obj)
385         for act in values:
386             if act[0] == 0:
387                 act[2][self._fields_id] = id
388                 obj.create(cr, user, act[2], context=context)
389             elif act[0] == 1:
390                 obj.write(cr, user, [act[1]], act[2], context=context)
391             elif act[0] == 2:
392                 obj.unlink(cr, user, [act[1]], context=context)
393             elif act[0] == 3:
394                 obj.datas[act[1]][self._fields_id] = False
395             elif act[0] == 4:
396                 obj.datas[act[1]] = id
397             elif act[0] == 5:
398                 for o in obj.datas.values():
399                     if o[self._fields_id] == id:
400                         o[self._fields_id] = False
401             elif act[0] == 6:
402                 for id2 in (act[2] or []):
403                     obj.datas[id2][self._fields_id] = id
404
405     def search_memory(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, operator='like', context=None):
406         raise _('Not Implemented')
407
408     def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
409         if not context:
410             context = {}
411         if not values:
412             values = {}
413         res = {}
414         for id in ids:
415             res[id] = []
416         ids2 = obj.pool.get(self._obj).search(cr, user, [(self._fields_id, 'in', ids)], limit=self._limit)
417         for r in obj.pool.get(self._obj)._read_flat(cr, user, ids2, [self._fields_id], context=context, load='_classic_write'):
418             res[r[self._fields_id]].append(r['id'])
419         return res
420
421     def set(self, cr, obj, id, field, values, user=None, context=None):
422         if not context:
423             context = {}
424         if not values:
425             return
426         _table = obj.pool.get(self._obj)._table
427         obj = obj.pool.get(self._obj)
428         for act in values:
429             if act[0] == 0:
430                 act[2][self._fields_id] = id
431                 obj.create(cr, user, act[2], context=context)
432             elif act[0] == 1:
433                 obj.write(cr, user, [act[1]], act[2], context=context)
434             elif act[0] == 2:
435                 obj.unlink(cr, user, [act[1]], context=context)
436             elif act[0] == 3:
437                 cr.execute('update '+_table+' set '+self._fields_id+'=null where id=%s', (act[1],))
438             elif act[0] == 4:
439                 cr.execute('update '+_table+' set '+self._fields_id+'=%s where id=%s', (id, act[1]))
440             elif act[0] == 5:
441                 cr.execute('update '+_table+' set '+self._fields_id+'=null where '+self._fields_id+'=%s', (id,))
442             elif act[0] == 6:
443                 if not act[2]:
444                     ids2 = [0]
445                 else:
446                     ids2 = act[2]
447                 cr.execute('update '+_table+' set '+self._fields_id+'=NULL where '+self._fields_id+'=%s and id not in ('+','.join(map(str, ids2))+')', (id,))
448                 if act[2]:
449                     cr.execute('update '+_table+' set '+self._fields_id+'=%s where id in ('+','.join(map(str, act[2]))+')', (id,))
450
451     def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, operator='like'):
452         return obj.pool.get(self._obj).name_search(cr, uid, value, self._domain, offset, limit)
453
454
455 #
456 # Values: (0, 0,  { fields })    create
457 #         (1, ID, { fields })    modification
458 #         (2, ID)                remove
459 #         (3, ID)                unlink
460 #         (4, ID)                link
461 #         (5, ID)                unlink all
462 #         (6, ?, ids)            set a list of links
463 #
464 class many2many(_column):
465     _classic_read = False
466     _classic_write = False
467     _type = 'many2many'
468
469     def __init__(self, obj, rel, id1, id2, string='unknown', limit=None, **args):
470         _column.__init__(self, string=string, **args)
471         self._obj = obj
472         if '.' in rel:
473             raise Exception(_('The second argument of the many2many field %s must be a SQL table !'\
474                 'You used %s, which is not a valid SQL table name.')% (string,rel))
475         self._rel = rel
476         self._id1 = id1
477         self._id2 = id2
478         self._limit = limit
479
480     def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
481         if not context:
482             context = {}
483         if not values:
484             values = {}
485         res = {}
486         if not ids:
487             return res
488         for id in ids:
489             res[id] = []
490         ids_s = ','.join(map(str, ids))
491         limit_str = self._limit is not None and ' limit %d' % self._limit or ''
492         obj = obj.pool.get(self._obj)
493
494         d1, d2 = obj.pool.get('ir.rule').domain_get(cr, user, obj._name)
495         if d1:
496             d1 = ' and ' + d1
497
498         cr.execute('SELECT '+self._rel+'.'+self._id2+','+self._rel+'.'+self._id1+' \
499                 FROM '+self._rel+' , '+obj._table+' \
500                 WHERE '+self._rel+'.'+self._id1+' in ('+ids_s+') \
501                     AND '+self._rel+'.'+self._id2+' = '+obj._table+'.id '+d1
502                 +limit_str+' order by '+obj._table+'.'+obj._order+' offset %s',
503                 d2+[offset])
504         for r in cr.fetchall():
505             res[r[1]].append(r[0])
506         return res
507
508     def set(self, cr, obj, id, name, values, user=None, context=None):
509         if not context:
510             context = {}
511         if not values:
512             return
513         obj = obj.pool.get(self._obj)
514         for act in values:
515             if act[0] == 0:
516                 idnew = obj.create(cr, user, act[2])
517                 cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%s,%s)', (id, idnew))
518             elif act[0] == 1:
519                 obj.write(cr, user, [act[1]], act[2], context=context)
520             elif act[0] == 2:
521                 obj.unlink(cr, user, [act[1]], context=context)
522             elif act[0] == 3:
523                 cr.execute('delete from '+self._rel+' where ' + self._id1 + '=%s and '+ self._id2 + '=%s', (id, act[1]))
524             elif act[0] == 4:
525                 cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%s,%s)', (id, act[1]))
526             elif act[0] == 5:
527                 cr.execute('update '+self._rel+' set '+self._id2+'=null where '+self._id2+'=%s', (id,))
528             elif act[0] == 6:
529
530                 d1, d2 = obj.pool.get('ir.rule').domain_get(cr, user, obj._name)
531                 if d1:
532                     d1 = ' and ' + d1
533                 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)
534
535                 for act_nbr in act[2]:
536                     cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%s, %s)', (id, act_nbr))
537
538     #
539     # TODO: use a name_search
540     #
541     def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, operator='like'):
542         return obj.pool.get(self._obj).search(cr, uid, args+self._domain+[('name', operator, value)], offset, limit)
543
544     def get_memory(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
545         result = {}
546         for id in ids:
547             result[id] = obj.datas[id].get(name, [])
548         return result
549
550     def set_memory(self, cr, obj, id, name, values, user=None, context=None):
551         if not values:
552             return
553         for act in values:
554             # TODO: use constants instead of these magic numbers
555             if act[0] == 0:
556                 raise _('Not Implemented')
557             elif act[0] == 1:
558                 raise _('Not Implemented')
559             elif act[0] == 2:
560                 raise _('Not Implemented')
561             elif act[0] == 3:
562                 raise _('Not Implemented')
563             elif act[0] == 4:
564                 raise _('Not Implemented')
565             elif act[0] == 5:
566                 raise _('Not Implemented')
567             elif act[0] == 6:
568                 obj.datas[id][name] = act[2]
569
570
571 # ---------------------------------------------------------
572 # Function fields
573 # ---------------------------------------------------------
574 class function(_column):
575     _classic_read = False
576     _classic_write = False
577     _type = 'function'
578     _properties = True
579
580 #
581 # multi: compute several fields in one call
582 #
583     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):
584         _column.__init__(self, **args)
585         self._obj = obj
586         self._method = method
587         self._fnct = fnct
588         self._fnct_inv = fnct_inv
589         self._arg = arg
590         self._multi = multi
591         if 'relation' in args:
592             self._obj = args['relation']
593         self._fnct_inv_arg = fnct_inv_arg
594         if not fnct_inv:
595             self.readonly = 1
596         self._type = type
597         self._fnct_search = fnct_search
598         self.store = store
599         if store:
600             self._classic_read = True
601             self._classic_write = True
602         if type == 'float':
603             self._symbol_c = float._symbol_c
604             self._symbol_f = float._symbol_f
605             self._symbol_set = float._symbol_set
606
607     def search(self, cr, uid, obj, name, args):
608         if not self._fnct_search:
609             #CHECKME: should raise an exception
610             return []
611         return self._fnct_search(obj, cr, uid, obj, name, args)
612
613     def get(self, cr, obj, ids, name, user=None, context=None, values=None):
614         if not context:
615             context = {}
616         if not values:
617             values = {}
618         res = {}
619         if self._method:
620             res = self._fnct(obj, cr, user, ids, name, self._arg, context)
621         else:
622             res = self._fnct(cr, obj._table, ids, name, self._arg, context)
623
624         if self._type == 'binary' and context.get('bin_size', False):
625             # convert the data returned by the function with the size of that data...
626             res = dict(map(lambda (x, y): (x, tools.human_size(len(y))), res.items()))
627         return res
628
629     def set(self, cr, obj, id, name, value, user=None, context=None):
630         if not context:
631             context = {}
632         if self._fnct_inv:
633             self._fnct_inv(obj, cr, user, id, name, value, self._fnct_inv_arg, context)
634
635 # ---------------------------------------------------------
636 # Related fields
637 # ---------------------------------------------------------
638
639 class related(function):
640
641     def _fnct_search(self, tobj, cr, uid, obj=None, name=None, context=None):
642         where_flag = 0
643         where = " where"
644         query = "select %s.id from %s" % (obj._table, obj._table)
645         relation_child = obj._name
646         relation = obj._name
647         for i in range(len(self._arg)):
648             field_detail = self._field_get(cr, uid, obj, relation, self._arg[i])
649             relation = field_detail[0]
650             if field_detail[1] in ('one2many', 'many2many'):
651                 obj_child = obj.pool.get(field_detail[2][self._arg[i]]['relation'])
652                 field_detail_child = obj_child.fields_get(cr, uid,)
653
654                 fields_filter = dict(filter(lambda x: x[1].get('relation', False)
655                                        and x[1].get('relation') == relation_child
656                                        and x[1].get('type')=='many2one', field_detail_child.items()))
657                 query += " inner join %s on %s.id = %s.%s" % (obj_child._table, obj._table, obj_child._table, fields_filter.keys()[0])
658                 relation_child = relation
659             elif field_detail[1] in ('many2one'):
660                 obj_child = obj.pool.get(field_detail[2][self._arg[i]]['relation'])
661                 obj_child2 = obj.pool.get(relation_child)
662                 if obj_child._name == obj_child2._name:
663 #                     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');
664 #                    where +=" %s.id = %s.%s in (select id from %s where %s.%s %s %s"%(obj_child._table,obj_child2._table,self._arg[i])
665                     pass
666                 else:
667                     query += " inner join %s on %s.id = %s.%s" % (obj_child._table, obj_child._table, obj_child2._table, self._arg[i])
668                 relation_child = field_detail[0]
669                 if i == (len(self._arg)-1):
670                     if obj_child._inherits:
671                         obj_child_inherits = obj.pool.get(obj_child._inherits.keys()[0])
672                         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])
673                         obj_child = obj_child_inherits
674                     where += " %s.%s %s '%%%s%%' and" % (obj_child._table, obj_child._rec_name, context[0][1], context[0][2])
675             else:
676                 obj_child = obj.pool.get(relation_child)
677                 if field_detail[1] in ('char'):
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 ('date'):
680                     where += " %s.%s %s '%s' and" % (obj_child._table, self._arg[i], context[0][1], context[0][2])
681                 if field_detail[1] in ['integer', 'long', 'float','integer_big']:
682                     where += " %s.%s %s '%s' and" % (obj_child._table, self._arg[i], context[0][1], context[0][2])
683         if len(where)>10:
684             query += where.rstrip('and')
685         cr.execute(query)
686         ids = []
687         for id in cr.fetchall():
688             ids.append(id[0])
689         return [('id', 'in', ids)]
690
691 #    def _fnct_write(self,obj,cr, uid, ids,values, field_name, args, context=None):
692 #        raise 'Not Implemented Yet'
693
694     def _fnct_read(self, obj, cr, uid, ids, field_name, args, context=None):
695         if not ids: return {}
696         relation = obj._name
697         res = {}
698         objlst = obj.browse(cr, uid, ids)
699         for data in objlst:
700             t_data = data
701             relation = obj._name
702             for i in range(len(self.arg)):
703                 field_detail = self._field_get(cr, uid, obj, relation, self.arg[i])
704                 relation = field_detail[0]
705                 if not t_data[self.arg[i]]:
706                     t_data = False
707                     break
708                 if field_detail[1] in ('one2many', 'many2many'):
709                     t_data = t_data[self.arg[i]][0]
710                 else:
711                     t_data = t_data[self.arg[i]]
712             if type(t_data) == type(objlst[0]):
713                 res[data.id] = (t_data.id,t_data.name)
714             else:
715                 res[data.id] = t_data
716         return res
717
718     def __init__(self, *arg, **args):
719         self.arg = arg
720         super(related, self).__init__(self._fnct_read, arg, fnct_inv_arg=arg, method=True, fnct_search=self._fnct_search, **args)
721
722     # TODO: call field_get on the object, not in the DB
723     def _field_get(self, cr, uid, obj, model_name, prop):
724         fields = obj.pool.get(model_name).fields_get(cr, uid,[prop])
725         if fields.get(prop, False):
726             return(fields[prop].get('relation', False), fields[prop].get('type', False), fields)
727         else:
728             raise 'Field %s not exist in %s' % (prop, model_name)
729
730
731 # ---------------------------------------------------------
732 # Serialized fields
733 # ---------------------------------------------------------
734 class serialized(_column):
735     def __init__(self, string='unknown', serialize_func=repr, deserialize_func=eval, type='text', **args):
736         self._serialize_func = serialize_func
737         self._deserialize_func = deserialize_func
738         self._type = type
739         self._symbol_set = (self._symbol_c, self._serialize_func)
740         self._symbol_get = self._deserialize_func
741         super(serialized, self).__init__(string=string, **args)
742
743
744 class property(function):
745
746     def _fnct_write(self, obj, cr, uid, id, prop, id_val, val, context=None):
747         if not context:
748             context = {}
749         (obj_dest,) = val
750         definition_id = self._field_get(cr, uid, obj._name, prop)
751
752         property = obj.pool.get('ir.property')
753         nid = property.search(cr, uid, [('fields_id', '=', definition_id),
754             ('res_id', '=', obj._name+','+str(id))])
755         while len(nid):
756             cr.execute('DELETE FROM ir_property WHERE id=%s', (nid.pop(),))
757
758         nid = property.search(cr, uid, [('fields_id', '=', definition_id),
759             ('res_id', '=', False)])
760         default_val = False
761         if nid:
762             default_val = property.browse(cr, uid, nid[0], context).value
763
764         company_id = obj.pool.get('res.users').company_get(cr, uid, uid)
765         res = False
766         newval = (id_val and obj_dest+','+str(id_val)) or False
767         if (newval != default_val) and newval:
768             propdef = obj.pool.get('ir.model.fields').browse(cr, uid,
769                     definition_id, context=context)
770             res = property.create(cr, uid, {
771                 'name': propdef.name,
772                 'value': newval,
773                 'res_id': obj._name+','+str(id),
774                 'company_id': company_id,
775                 'fields_id': definition_id
776             }, context=context)
777         return res
778
779     def _fnct_read(self, obj, cr, uid, ids, prop, val, context=None):
780         if not context:
781             context = {}
782         property = obj.pool.get('ir.property')
783         definition_id = self._field_get(cr, uid, obj._name, prop)
784
785         nid = property.search(cr, uid, [('fields_id', '=', definition_id),
786             ('res_id', '=', False)])
787         default_val = False
788         if nid:
789             d = property.browse(cr, uid, nid[0], context).value
790             default_val = (d and int(d.split(',')[1])) or False
791
792         vids = [obj._name + ',' + str(id) for id in  ids]
793         nids = property.search(cr, uid, [('fields_id', '=', definition_id),
794             ('res_id', 'in', vids)])
795
796         res = {}
797         for id in ids:
798             res[id] = default_val
799         for prop in property.browse(cr, uid, nids):
800             res[int(prop.res_id.split(',')[1])] = (prop.value and \
801                     int(prop.value.split(',')[1])) or False
802
803         obj = obj.pool.get(self._obj)
804         names = dict(obj.name_get(cr, uid, filter(None, res.values()), context))
805         for r in res.keys():
806             if res[r] and res[r] in names:
807                 res[r] = (res[r], names[res[r]])
808             else:
809                 res[r] = False
810         return res
811
812     def _field_get(self, cr, uid, model_name, prop):
813         if not self.field_id.get(cr.dbname):
814             cr.execute('SELECT id \
815                     FROM ir_model_fields \
816                     WHERE name=%s AND model=%s', (prop, model_name))
817             res = cr.fetchone()
818             self.field_id[cr.dbname] = res and res[0]
819         return self.field_id[cr.dbname]
820
821     def __init__(self, obj_prop, **args):
822         self.field_id = {}
823         function.__init__(self, self._fnct_read, False, self._fnct_write,
824                 (obj_prop, ), **args)
825
826     def restart(self):
827         self.field_id = {}
828
829
830 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
831