1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU Affero General Public License as
9 # published by the Free Software Foundation, either version 3 of the
10 # License, or (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU Affero General Public License for more details.
17 # You should have received a copy of the GNU Affero General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
20 ##############################################################################
24 # - relations (one2many, many2one, many2many)
28 # _classic_read: is a classic sql fields
40 from psycopg2 import Binary
43 from tools.translate import _
45 def _symbol_set(symb):
46 if symb == None or symb == False:
48 elif isinstance(symb, unicode):
49 return symb.encode('utf-8')
53 class _column(object):
62 _symbol_f = _symbol_set
63 _symbol_set = (_symbol_c, _symbol_f)
66 def __init__(self, string='unknown', required=False, readonly=False, domain=None, context=None, states=None, priority=0, change_default=False, size=None, ondelete="set null", translate=False, select=False, **args):
71 self.states = states or {}
73 self.readonly = readonly
74 self.required = required
76 self.help = args.get('help', '')
77 self.priority = priority
78 self.change_default = change_default
79 self.ondelete = ondelete
80 self.translate = translate
82 self._context = context
87 self.selectable = True
88 self.group_operator = args.get('group_operator', False)
91 setattr(self, a, args[a])
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=%s', (self._symbol_set[1](value), id))
99 def set_memory(self, cr, obj, id, name, value, user=None, context=None):
100 raise Exception(_('Not implemented set_memory method !'))
102 def get_memory(self, cr, obj, ids, name, user=None, context=None, values=None):
103 raise Exception(_('Not implemented get_memory method !'))
105 def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
106 raise Exception(_('undefined get method !'))
108 def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, context=None):
109 ids = obj.search(cr, uid, args+self._domain+[(name, 'ilike', value)], offset, limit, context=context)
110 res = obj.read(cr, uid, ids, [name], context=context)
111 return [x[name] for x in res]
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 !'))
117 # ---------------------------------------------------------
119 # ---------------------------------------------------------
120 class boolean(_column):
123 _symbol_f = lambda x: x and 'True' or 'False'
124 _symbol_set = (_symbol_c, _symbol_f)
126 class integer_big(_column):
127 _type = 'integer_big'
129 _symbol_f = lambda x: int(x or 0)
130 _symbol_set = (_symbol_c, _symbol_f)
131 _symbol_get = lambda self,x: x or 0
133 class integer(_column):
136 _symbol_f = lambda x: int(x or 0)
137 _symbol_set = (_symbol_c, _symbol_f)
138 _symbol_get = lambda self,x: x or 0
141 class reference(_column):
143 def __init__(self, string, selection, size, **args):
144 _column.__init__(self, string=string, size=size, selection=selection, **args)
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)
154 # takes a string (encoded in utf8) and returns a string (encoded in utf8)
155 def _symbol_set_char(self, symb):
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:
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 u_symb = tools.ustr(symb)
167 return u_symb[:self.size].encode('utf8')
175 class float(_column):
178 _symbol_f = lambda x: __builtin__.float(x or 0.0)
179 _symbol_set = (_symbol_c, _symbol_f)
180 _symbol_get = lambda self,x: x or 0.0
182 def __init__(self, string='unknown', digits=None, digits_compute=None, **args):
183 _column.__init__(self, string=string, **args)
185 self.digits_compute = digits_compute
188 def digits_change(self, cr):
189 if self.digits_compute:
190 t = self.digits_compute(cr)
191 self._symbol_set=('%s', lambda x: ('%.'+str(t[1])+'f') % (__builtin__.float(x or 0.0),))
198 """ Returns the current date in a format fit for being a
199 default value to a ``date`` field.
201 This method should be provided as is to the _defaults dict, it
202 should not be called.
204 return DT.date.today().strftime(
205 tools.DEFAULT_SERVER_DATE_FORMAT)
207 class datetime(_column):
211 """ Returns the current datetime in a format fit for being a
212 default value to a ``datetime`` field.
214 This method should be provided as is to the _defaults dict, it
215 should not be called.
217 return DT.datetime.now().strftime(
218 tools.DEFAULT_SERVER_DATETIME_FORMAT)
224 """ Returns the current time in a format fit for being a
225 default value to a ``time`` field.
227 This method should be proivided as is to the _defaults dict,
228 it should not be called.
230 return DT.datetime.now().strftime(
231 tools.DEFAULT_SERVER_TIME_FORMAT)
233 class binary(_column):
236 _symbol_f = lambda symb: symb and Binary(symb) or None
237 _symbol_set = (_symbol_c, _symbol_f)
238 _symbol_get = lambda self, x: x and str(x)
240 _classic_read = False
243 def __init__(self, string='unknown', filters=None, **args):
244 _column.__init__(self, string=string, **args)
245 self.filters = filters
247 def get_memory(self, cr, obj, ids, name, user=None, context=None, values=None):
260 # If client is requesting only the size of the field, we return it instead
261 # of the content. Presumably a separate request will be done to read the actual
262 # content if it's needed at some point.
263 # TODO: after 6.0 we should consider returning a dict with size and content instead of
264 # having an implicit convention for the value
265 if val and context.get('bin_size_%s' % name, context.get('bin_size')):
266 res[i] = tools.human_size(long(val))
274 class selection(_column):
277 def __init__(self, selection, string='unknown', **args):
278 _column.__init__(self, string=string, **args)
279 self.selection = selection
281 # ---------------------------------------------------------
283 # ---------------------------------------------------------
286 # Values: (0, 0, { fields }) create
287 # (1, ID, { fields }) update
288 # (2, ID) remove (delete)
289 # (3, ID) unlink one (target id or target of relation)
291 # (5) unlink all (only valid for one2many)
293 #CHECKME: dans la pratique c'est quoi la syntaxe utilisee pour le 5? (5) ou (5, 0)?
294 class one2one(_column):
295 _classic_read = False
296 _classic_write = True
299 def __init__(self, obj, string='unknown', **args):
300 warnings.warn("The one2one field doesn't work anymore", DeprecationWarning)
301 _column.__init__(self, string=string, **args)
304 def set(self, cr, obj_src, id, field, act, user=None, context=None):
307 obj = obj_src.pool.get(self._obj)
308 self._table = obj_src.pool.get(self._obj)._table
310 id_new = obj.create(cr, user, act[1])
311 cr.execute('update '+obj_src._table+' set '+field+'=%s where id=%s', (id_new, id))
313 cr.execute('select '+field+' from '+obj_src._table+' where id=%s', (act[0],))
314 id = cr.fetchone()[0]
315 obj.write(cr, user, [id], act[1], context=context)
317 def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, context=None):
318 return obj.pool.get(self._obj).search(cr, uid, args+self._domain+[('name', 'like', value)], offset, limit, context=context)
321 class many2one(_column):
322 _classic_read = False
323 _classic_write = True
326 _symbol_f = lambda x: x or None
327 _symbol_set = (_symbol_c, _symbol_f)
329 def __init__(self, obj, string='unknown', **args):
330 _column.__init__(self, string=string, **args)
333 def set_memory(self, cr, obj, id, field, values, user=None, context=None):
334 obj.datas.setdefault(id, {})
335 obj.datas[id][field] = values
337 def get_memory(self, cr, obj, ids, name, user=None, context=None, values=None):
340 result[id] = obj.datas[id].get(name, False)
343 def get(self, cr, obj, ids, name, user=None, context=None, values=None):
351 res[r['id']] = r[name]
353 res.setdefault(id, '')
354 obj = obj.pool.get(self._obj)
356 # build a dictionary of the form {'id_of_distant_resource': name_of_distant_resource}
357 # we use uid=1 because the visibility of a many2one field value (just id and name)
358 # must be the access right of the parent form and not the linked object itself.
359 records = dict(obj.name_get(cr, 1, list(set(filter(None, res.values()))), context=context))
361 if res[id] in records:
362 res[id] = (res[id], records[res[id]])
367 def set(self, cr, obj_src, id, field, values, user=None, context=None):
370 obj = obj_src.pool.get(self._obj)
371 self._table = obj_src.pool.get(self._obj)._table
372 if type(values) == type([]):
375 id_new = obj.create(cr, act[2])
376 cr.execute('update '+obj_src._table+' set '+field+'=%s where id=%s', (id_new, id))
378 obj.write(cr, [act[1]], act[2], context=context)
380 cr.execute('delete from '+self._table+' where id=%s', (act[1],))
381 elif act[0] == 3 or act[0] == 5:
382 cr.execute('update '+obj_src._table+' set '+field+'=null where id=%s', (id,))
384 cr.execute('update '+obj_src._table+' set '+field+'=%s where id=%s', (act[1], id))
387 cr.execute('update '+obj_src._table+' set '+field+'=%s where id=%s', (values, id))
389 cr.execute('update '+obj_src._table+' set '+field+'=null where id=%s', (id,))
391 def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, context=None):
392 return obj.pool.get(self._obj).search(cr, uid, args+self._domain+[('name', 'like', value)], offset, limit, context=context)
395 class one2many(_column):
396 _classic_read = False
397 _classic_write = False
401 def __init__(self, obj, fields_id, string='unknown', limit=None, **args):
402 _column.__init__(self, string=string, **args)
404 self._fields_id = fields_id
406 #one2many can't be used as condition for defaults
407 assert(self.change_default != True)
409 def get_memory(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
413 context = context.copy()
414 context.update(self._context)
420 ids2 = obj.pool.get(self._obj).search(cr, user, [(self._fields_id, 'in', ids)], limit=self._limit, context=context)
421 for r in obj.pool.get(self._obj).read(cr, user, ids2, [self._fields_id], context=context, load='_classic_write'):
422 if r[self._fields_id] in res:
423 res[r[self._fields_id]].append(r['id'])
426 def set_memory(self, cr, obj, id, field, values, user=None, context=None):
430 context = context.copy()
431 context.update(self._context)
434 obj = obj.pool.get(self._obj)
437 act[2][self._fields_id] = id
438 obj.create(cr, user, act[2], context=context)
440 obj.write(cr, user, [act[1]], act[2], context=context)
442 obj.unlink(cr, user, [act[1]], context=context)
444 obj.datas[act[1]][self._fields_id] = False
446 obj.datas[act[1]] = id
448 for o in obj.datas.values():
449 if o[self._fields_id] == id:
450 o[self._fields_id] = False
452 for id2 in (act[2] or []):
453 obj.datas[id2][self._fields_id] = id
455 def search_memory(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, operator='like', context=None):
456 raise _('Not Implemented')
458 def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
462 context = context.copy()
463 context.update(self._context)
471 ids2 = obj.pool.get(self._obj).search(cr, user, self._domain + [(self._fields_id, 'in', ids)], limit=self._limit, context=context)
472 for r in obj.pool.get(self._obj)._read_flat(cr, user, ids2, [self._fields_id], context=context, load='_classic_write'):
473 if r[self._fields_id] in res:
474 res[r[self._fields_id]].append(r['id'])
477 def set(self, cr, obj, id, field, values, user=None, context=None):
482 context = context.copy()
483 context.update(self._context)
484 context['no_store_function'] = True
487 _table = obj.pool.get(self._obj)._table
488 obj = obj.pool.get(self._obj)
491 act[2][self._fields_id] = id
492 id_new = obj.create(cr, user, act[2], context=context)
493 result += obj._store_get_values(cr, user, [id_new], act[2].keys(), context)
495 obj.write(cr, user, [act[1]], act[2], context=context)
497 obj.unlink(cr, user, [act[1]], context=context)
499 cr.execute('update '+_table+' set '+self._fields_id+'=null where id=%s', (act[1],))
501 cr.execute('update '+_table+' set '+self._fields_id+'=%s where id=%s', (id, act[1]))
503 cr.execute('update '+_table+' set '+self._fields_id+'=null where '+self._fields_id+'=%s', (id,))
505 obj.write(cr, user, act[2], {self._fields_id:id}, context=context or {})
507 cr.execute('select id from '+_table+' where '+self._fields_id+'=%s and id <> ALL (%s)', (id,ids2))
508 ids3 = map(lambda x:x[0], cr.fetchall())
509 obj.write(cr, user, ids3, {self._fields_id:False}, context=context or {})
512 def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, operator='like', context=None):
513 return obj.pool.get(self._obj).name_search(cr, uid, value, self._domain, operator, context=context,limit=limit)
517 # Values: (0, 0, { fields }) create
518 # (1, ID, { fields }) update (write fields to ID)
519 # (2, ID) remove (calls unlink on ID, that will also delete the relationship because of the ondelete)
520 # (3, ID) unlink (delete the relationship between the two objects but does not delete ID)
521 # (4, ID) link (add a relationship)
523 # (6, ?, ids) set a list of links
525 class many2many(_column):
526 _classic_read = False
527 _classic_write = False
530 def __init__(self, obj, rel, id1, id2, string='unknown', limit=None, **args):
531 _column.__init__(self, string=string, **args)
534 raise Exception(_('The second argument of the many2many field %s must be a SQL table !'\
535 'You used %s, which is not a valid SQL table name.')% (string,rel))
541 def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
552 warnings.warn("Specifying offset at a many2many.get() may produce unpredictable results.",
553 DeprecationWarning, stacklevel=2)
554 obj = obj.pool.get(self._obj)
556 # static domains are lists, and are evaluated both here and on client-side, while string
557 # domains supposed by dynamic and evaluated on client-side only (thus ignored here)
558 # FIXME: make this distinction explicit in API!
559 domain = isinstance(self._domain, list) and self._domain or []
561 wquery = obj._where_calc(cr, user, domain, context=context)
562 obj._apply_ir_rules(cr, user, wquery, 'read', context=context)
563 from_c, where_c, where_params = wquery.get_sql()
565 where_c = ' AND ' + where_c
567 if offset or self._limit:
568 order_by = ' ORDER BY "%s".%s' %(obj._table, obj._order.split(',')[0])
573 if self._limit is not None:
574 limit_str = ' LIMIT %d' % self._limit
576 query = 'SELECT %(rel)s.%(id2)s, %(rel)s.%(id1)s \
577 FROM %(rel)s, %(from_c)s \
578 WHERE %(rel)s.%(id1)s IN %%s \
579 AND %(rel)s.%(id2)s = %(tbl)s.id \
591 'order_by': order_by,
594 cr.execute(query, [tuple(ids),] + where_params)
595 for r in cr.fetchall():
596 res[r[1]].append(r[0])
599 def set(self, cr, obj, id, name, values, user=None, context=None):
604 obj = obj.pool.get(self._obj)
606 if not (isinstance(act, list) or isinstance(act, tuple)) or not act:
609 idnew = obj.create(cr, user, act[2])
610 cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%s,%s)', (id, idnew))
612 obj.write(cr, user, [act[1]], act[2], context=context)
614 obj.unlink(cr, user, [act[1]], context=context)
616 cr.execute('delete from '+self._rel+' where ' + self._id1 + '=%s and '+ self._id2 + '=%s', (id, act[1]))
618 cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%s,%s)', (id, act[1]))
620 cr.execute('update '+self._rel+' set '+self._id2+'=null where '+self._id2+'=%s', (id,))
623 d1, d2,tables = obj.pool.get('ir.rule').domain_get(cr, user, obj._name, context=context)
625 d1 = ' and ' + ' and '.join(d1)
628 cr.execute('delete from '+self._rel+' where '+self._id1+'=%s AND '+self._id2+' IN (SELECT '+self._rel+'.'+self._id2+' FROM '+self._rel+', '+','.join(tables)+' WHERE '+self._rel+'.'+self._id1+'=%s AND '+self._rel+'.'+self._id2+' = '+obj._table+'.id '+ d1 +')', [id, id]+d2)
630 for act_nbr in act[2]:
631 cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%s, %s)', (id, act_nbr))
634 # TODO: use a name_search
636 def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, operator='like', context=None):
637 return obj.pool.get(self._obj).search(cr, uid, args+self._domain+[('name', operator, value)], offset, limit, context=context)
639 def get_memory(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
642 result[id] = obj.datas[id].get(name, [])
645 def set_memory(self, cr, obj, id, name, values, user=None, context=None):
649 # TODO: use constants instead of these magic numbers
651 raise _('Not Implemented')
653 raise _('Not Implemented')
655 raise _('Not Implemented')
657 raise _('Not Implemented')
659 raise _('Not Implemented')
661 raise _('Not Implemented')
663 obj.datas[id][name] = act[2]
666 def get_nice_size(a):
668 if isinstance(y, (int,long)):
674 return (x, tools.human_size(size))
676 # ---------------------------------------------------------
678 # ---------------------------------------------------------
679 class function(_column):
680 _classic_read = False
681 _classic_write = False
687 # multi: compute several fields in one call
689 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):
690 _column.__init__(self, **args)
692 self._method = method
694 self._fnct_inv = fnct_inv
697 if 'relation' in args:
698 self._obj = args['relation']
700 self.digits = args.get('digits', (16,2))
701 self.digits_compute = args.get('digits_compute', None)
703 self._fnct_inv_arg = fnct_inv_arg
707 self._fnct_search = fnct_search
710 if not fnct_search and not store:
711 self.selectable = False
714 if self._type != 'many2one':
715 # m2o fields need to return tuples with name_get, not just foreign keys
716 self._classic_read = True
717 self._classic_write = True
719 self._symbol_get=lambda x:x and str(x)
722 self._symbol_c = float._symbol_c
723 self._symbol_f = float._symbol_f
724 self._symbol_set = float._symbol_set
726 if type == 'boolean':
727 self._symbol_c = boolean._symbol_c
728 self._symbol_f = boolean._symbol_f
729 self._symbol_set = boolean._symbol_set
731 def digits_change(self, cr):
732 if self.digits_compute:
733 t = self.digits_compute(cr)
734 self._symbol_set=('%s', lambda x: ('%.'+str(t[1])+'f') % (__builtin__.float(x or 0.0),))
738 def search(self, cr, uid, obj, name, args, context=None):
739 if not self._fnct_search:
740 #CHECKME: should raise an exception
742 return self._fnct_search(obj, cr, uid, obj, name, args, context=context)
744 def get(self, cr, obj, ids, name, user=None, context=None, values=None):
751 res = self._fnct(obj, cr, user, ids, name, self._arg, context)
753 res = self._fnct(cr, obj._table, ids, name, self._arg, context)
755 if self._type == "many2one" :
756 # Filtering only integer/long values if passed
757 res_ids = [x for x in res.values() if x and isinstance(x, (int,long))]
760 obj_model = obj.pool.get(self._obj)
761 dict_names = dict(obj_model.name_get(cr, user, res_ids, context))
763 if res[r] and res[r] in dict_names:
764 res[r] = (res[r], dict_names[res[r]])
766 if self._type == 'binary' and context.get('bin_size', False):
767 # convert the data returned by the function with the size of that data...
768 res = dict(map( get_nice_size, res.items()))
769 if self._type == "integer":
771 # Converting value into string so that it does not affect XML-RPC Limits
772 if isinstance(res[r],dict): # To treat integer values with _multi attribute
773 for record in res[r].keys():
774 res[r][record] = str(res[r][record])
780 def set(self, cr, obj, id, name, value, user=None, context=None):
784 self._fnct_inv(obj, cr, user, id, name, value, self._fnct_inv_arg, context)
787 # ---------------------------------------------------------
789 # ---------------------------------------------------------
791 class related(function):
793 def _fnct_search(self, tobj, cr, uid, obj=None, name=None, domain=None, context=None):
794 self._field_get2(cr, uid, obj, context)
798 if type(sarg) in [type([]), type( (1,) )]:
799 where = [(self._arg[i], 'in', sarg)]
801 where = [(self._arg[i], '=', sarg)]
803 where = map(lambda x: (self._arg[i],x[1], x[2]), domain)
805 sarg = obj.pool.get(self._relations[i]['object']).search(cr, uid, where, context=context)
807 return [(self._arg[0], 'in', sarg)]
809 def _fnct_write(self,obj,cr, uid, ids, field_name, values, args, context=None):
810 self._field_get2(cr, uid, obj, context=context)
811 if type(ids) != type([]):
813 objlst = obj.browse(cr, uid, ids)
817 for i in range(len(self.arg)):
819 field_detail = self._relations[i]
820 if not t_data[self.arg[i]]:
821 if self._type not in ('one2many', 'many2many'):
824 elif field_detail['type'] in ('one2many', 'many2many'):
825 if self._type != "many2one":
827 t_data = t_data[self.arg[i]][0]
832 t_data = t_data[self.arg[i]]
834 model = obj.pool.get(self._relations[-1]['object'])
835 model.write(cr, uid, [t_id], {args[-1]: values}, context=context)
837 def _fnct_read(self, obj, cr, uid, ids, field_name, args, context=None):
838 self._field_get2(cr, uid, obj, context)
839 if not ids: return {}
841 if self._type in ('one2many', 'many2many'):
842 res = dict([(i, []) for i in ids])
844 res = {}.fromkeys(ids, False)
846 objlst = obj.browse(cr, 1, ids, context=context)
852 for i in range(len(self.arg)):
853 field_detail = self._relations[i]
854 relation = field_detail['object']
856 if not t_data[self.arg[i]]:
862 if field_detail['type'] in ('one2many', 'many2many') and i != len(self.arg) - 1:
863 t_data = t_data[self.arg[i]][0]
865 t_data = t_data[self.arg[i]]
866 if type(t_data) == type(objlst[0]):
867 res[data.id] = t_data.id
869 res[data.id] = t_data
870 if self._type=='many2one':
871 ids = filter(None, res.values())
873 ng = dict(obj.pool.get(self._obj).name_get(cr, 1, ids, context=context))
876 res[r] = (res[r], ng[res[r]])
877 elif self._type in ('one2many', 'many2many'):
880 res[r] = [x.id for x in res[r]]
883 def __init__(self, *arg, **args):
886 super(related, self).__init__(self._fnct_read, arg, self._fnct_write, fnct_inv_arg=arg, method=True, fnct_search=self._fnct_search, **args)
887 if self.store is True:
888 # TODO: improve here to change self.store = {...} according to related objects
891 def _field_get2(self, cr, uid, obj, context=None):
895 for i in range(len(self._arg)):
896 f = obj.pool.get(obj_name).fields_get(cr, uid, [self._arg[i]], context=context)[self._arg[i]]
897 self._relations.append({
902 if f.get('relation',False):
903 obj_name = f['relation']
904 self._relations[-1]['relation'] = f['relation']
906 # ---------------------------------------------------------
908 # ---------------------------------------------------------
910 class dummy(function):
911 def _fnct_search(self, tobj, cr, uid, obj=None, name=None, domain=None, context=None):
914 def _fnct_write(self, obj, cr, uid, ids, field_name, values, args, context=None):
917 def _fnct_read(self, obj, cr, uid, ids, field_name, args, context=None):
920 def __init__(self, *arg, **args):
923 super(dummy, self).__init__(self._fnct_read, arg, self._fnct_write, fnct_inv_arg=arg, method=True, fnct_search=None, **args)
925 # ---------------------------------------------------------
927 # ---------------------------------------------------------
928 class serialized(_column):
929 def __init__(self, string='unknown', serialize_func=repr, deserialize_func=eval, type='text', **args):
930 self._serialize_func = serialize_func
931 self._deserialize_func = deserialize_func
933 self._symbol_set = (self._symbol_c, self._serialize_func)
934 self._symbol_get = self._deserialize_func
935 super(serialized, self).__init__(string=string, **args)
938 # TODO: review completly this class for speed improvement
939 class property(function):
941 def _get_default(self, obj, cr, uid, prop_name, context=None):
942 return self._get_defaults(obj, cr, uid, [prop_name], context=None)[0][prop_name]
944 def _get_defaults(self, obj, cr, uid, prop_name, context=None):
945 prop = obj.pool.get('ir.property')
946 domain = [('fields_id.model', '=', obj._name), ('fields_id.name','in',prop_name), ('res_id','=',False)]
947 ids = prop.search(cr, uid, domain, context=context)
949 default_value = {}.fromkeys(prop_name, False)
950 for prop_rec in prop.browse(cr, uid, ids, context=context):
951 if default_value.get(prop_rec.fields_id.name, False):
953 value = prop.get_by_record(cr, uid, prop_rec, context=context) or False
954 default_value[prop_rec.fields_id.name] = value
955 if value and (prop_rec.type == 'many2one'):
956 replaces.setdefault(value._name, {})
957 replaces[value._name][value.id] = True
958 return default_value, replaces
960 def _get_by_id(self, obj, cr, uid, prop_name, ids, context=None):
961 prop = obj.pool.get('ir.property')
962 vids = [obj._name + ',' + str(oid) for oid in ids]
964 domain = [('fields_id.model', '=', obj._name), ('fields_id.name','in',prop_name)]
965 #domain = prop._get_domain(cr, uid, prop_name, obj._name, context)
967 domain = [('res_id', 'in', vids)] + domain
968 return prop.search(cr, uid, domain, context=context)
970 # TODO: to rewrite more clean
971 def _fnct_write(self, obj, cr, uid, id, prop_name, id_val, obj_dest, context=None):
975 nids = self._get_by_id(obj, cr, uid, [prop_name], [id], context)
977 cr.execute('DELETE FROM ir_property WHERE id IN %s', (tuple(nids),))
979 default_val = self._get_default(obj, cr, uid, prop_name, context)
981 if id_val is not default_val:
982 def_id = self._field_get(cr, uid, obj._name, prop_name)
983 company = obj.pool.get('res.company')
984 cid = company._company_default_get(cr, uid, obj._name, def_id,
986 propdef = obj.pool.get('ir.model.fields').browse(cr, uid, def_id,
988 prop = obj.pool.get('ir.property')
989 return prop.create(cr, uid, {
990 'name': propdef.name,
992 'res_id': obj._name+','+str(id),
1000 def _fnct_read(self, obj, cr, uid, ids, prop_name, obj_dest, context=None):
1001 properties = obj.pool.get('ir.property')
1002 domain = [('fields_id.model', '=', obj._name), ('fields_id.name','in',prop_name)]
1003 domain += [('res_id','in', [obj._name + ',' + str(oid) for oid in ids])]
1004 nids = properties.search(cr, uid, domain, context=context)
1005 default_val,replaces = self._get_defaults(obj, cr, uid, prop_name, context)
1009 res[id] = default_val.copy()
1011 brs = properties.browse(cr, uid, nids, context=context)
1013 value = properties.get_by_record(cr, uid, prop, context=context)
1014 res[prop.res_id.id][prop.fields_id.name] = value or False
1015 if value and (prop.type == 'many2one'):
1016 replaces.setdefault(value._name, {})
1017 replaces[value._name][value.id] = True
1019 for rep in replaces:
1020 replaces[rep] = dict(obj.pool.get(rep).name_get(cr, uid, replaces[rep].keys(), context=context))
1022 for prop in prop_name:
1024 if res[id][prop] and hasattr(res[id][prop], '_name'):
1025 res[id][prop] = (res[id][prop].id , replaces[res[id][prop]._name].get(res[id][prop].id, False))
1030 def _field_get(self, cr, uid, model_name, prop):
1031 if not self.field_id.get(cr.dbname):
1032 cr.execute('SELECT id \
1033 FROM ir_model_fields \
1034 WHERE name=%s AND model=%s', (prop, model_name))
1036 self.field_id[cr.dbname] = res and res[0]
1037 return self.field_id[cr.dbname]
1039 def __init__(self, obj_prop, **args):
1040 # TODO remove obj_prop parameter (use many2one type)
1042 function.__init__(self, self._fnct_read, False, self._fnct_write,
1043 obj_prop, multi='properties', **args)
1049 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: