1 # -*- encoding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved
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.
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.
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/>.
21 ##############################################################################
25 # - relations (one2many, many2one, many2many)
29 # _classic_read: is a classic sql fields
39 from psycopg2 import Binary
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='', states=None, priority=0, change_default=False, size=None, ondelete="set null", translate=False, select=False, **args):
67 self.states = states or {}
69 self.readonly = readonly
70 self.required = required
72 self.help = args.get('help', '')
73 self.priority = priority
74 self.change_default = change_default
75 self.ondelete = ondelete
76 self.translate = translate
77 self._domain = domain or []
78 self._context = context
83 self.selectable = True
86 setattr(self, a, args[a])
91 def set(self, cr, obj, id, name, value, user=None, context=None):
92 cr.execute('update '+obj._table+' set '+name+'='+self._symbol_set[0]+' where id=%s', (self._symbol_set[1](value), id))
94 def set_memory(self, cr, obj, id, name, value, user=None, context=None):
95 raise Exception(_('Not implemented set_memory method !'))
97 def get_memory(self, cr, obj, ids, name, user=None, context=None, values=None):
98 raise Exception(_('Not implemented get_memory method !'))
100 def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
101 raise Exception(_('undefined get method !'))
103 def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None):
104 ids = obj.search(cr, uid, args+self._domain+[(name, 'ilike', value)], offset, limit)
105 res = obj.read(cr, uid, ids, [name])
106 return [x[name] for x in res]
108 def search_memory(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, context=None):
109 raise Exception(_('Not implemented search_memory method !'))
112 # ---------------------------------------------------------
114 # ---------------------------------------------------------
115 class boolean(_column):
118 _symbol_f = lambda x: x and 'True' or 'False'
119 _symbol_set = (_symbol_c, _symbol_f)
122 class integer_big(_column):
123 _type = 'integer_big'
125 _symbol_f = lambda x: int(x or 0)
126 _symbol_set = (_symbol_c, _symbol_f)
128 class integer(_column):
131 _symbol_f = lambda x: int(x or 0)
132 _symbol_set = (_symbol_c, _symbol_f)
135 class reference(_column):
138 def __init__(self, string, selection, size, **args):
139 _column.__init__(self, string=string, size=size, selection=selection, **args)
145 def __init__(self, string, size, **args):
146 _column.__init__(self, string=string, size=size, **args)
147 self._symbol_set = (self._symbol_c, self._symbol_set_char)
149 # takes a string (encoded in utf8) and returns a string (encoded in utf8)
150 def _symbol_set_char(self, symb):
152 # * we need to remove the "symb==False" from the next line BUT
153 # for now too many things rely on this broken behavior
154 # * the symb==None test should be common to all data types
155 if symb == None or symb == False:
158 # we need to convert the string to a unicode object to be able
159 # to evaluate its length (and possibly truncate it) reliably
160 u_symb = tools.ustr(symb)
162 return u_symb[:self.size].encode('utf8')
170 class float(_column):
173 _symbol_f = lambda x: __builtin__.float(x or 0.0)
174 _symbol_set = (_symbol_c, _symbol_f)
176 def __init__(self, string='unknown', digits=None, **args):
177 _column.__init__(self, string=string, **args)
185 class datetime(_column):
193 class binary(_column):
196 _symbol_f = lambda symb: symb and Binary(symb) or None
197 _symbol_set = (_symbol_c, _symbol_f)
198 _symbol_get = lambda self, x: x and str(x)
200 _classic_read = False
203 def __init__(self, string='unknown', filters=None, **args):
204 _column.__init__(self, string=string, **args)
205 self.filters = filters
207 def get_memory(self, cr, obj, ids, name, user=None, context=None, values=None):
219 if context.get('bin_size', False) and val:
220 res[i] = tools.human_size(long(val))
228 class selection(_column):
231 def __init__(self, selection, string='unknown', **args):
232 _column.__init__(self, string=string, **args)
233 self.selection = selection
235 # ---------------------------------------------------------
237 # ---------------------------------------------------------
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)
245 # (5) unlink all (only valid for one2many)
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
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)
258 def set(self, cr, obj_src, id, field, act, user=None, context=None):
261 obj = obj_src.pool.get(self._obj)
262 self._table = obj_src.pool.get(self._obj)._table
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))
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)
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)
275 class many2one(_column):
276 _classic_read = False
277 _classic_write = True
280 _symbol_f = lambda x: x or None
281 _symbol_set = (_symbol_c, _symbol_f)
283 def __init__(self, obj, string='unknown', **args):
284 _column.__init__(self, string=string, **args)
287 def set_memory(self, cr, obj, id, field, values, user=None, context=None):
288 obj.datas.setdefault(id, {})
289 obj.datas[id][field] = values
291 def get_memory(self, cr, obj, ids, name, user=None, context=None, values=None):
294 result[id] = obj.datas[id][name]
297 def get(self, cr, obj, ids, name, user=None, context=None, values=None):
304 res[r['id']] = r[name]
306 res.setdefault(id, '')
307 obj = obj.pool.get(self._obj)
308 # build a dictionary of the form {'id_of_distant_resource': name_of_distant_resource}
309 from orm import except_orm
311 names = dict(obj.name_get(cr, user, filter(None, res.values()), context))
314 iids = filter(None, res.values())
316 names[iiid] = '// Access Denied //'
319 if res[r] and res[r] in names:
320 res[r] = (res[r], names[res[r]])
325 def set(self, cr, obj_src, id, field, values, user=None, context=None):
328 obj = obj_src.pool.get(self._obj)
329 self._table = obj_src.pool.get(self._obj)._table
330 if type(values) == type([]):
333 id_new = obj.create(cr, act[2])
334 cr.execute('update '+obj_src._table+' set '+field+'=%s where id=%s', (id_new, id))
336 obj.write(cr, [act[1]], act[2], context=context)
338 cr.execute('delete from '+self._table+' where id=%s', (act[1],))
339 elif act[0] == 3 or act[0] == 5:
340 cr.execute('update '+obj_src._table+' set '+field+'=null where id=%s', (id,))
342 cr.execute('update '+obj_src._table+' set '+field+'=%s where id=%s', (act[1], id))
345 cr.execute('update '+obj_src._table+' set '+field+'=%s where id=%s', (values, id))
347 cr.execute('update '+obj_src._table+' set '+field+'=null where id=%s', (id,))
349 def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None):
350 return obj.pool.get(self._obj).search(cr, uid, args+self._domain+[('name', 'like', value)], offset, limit)
353 class one2many(_column):
354 _classic_read = False
355 _classic_write = False
359 def __init__(self, obj, fields_id, string='unknown', limit=None, **args):
360 _column.__init__(self, string=string, **args)
362 self._fields_id = fields_id
364 #one2many can't be used as condition for defaults
365 assert(self.change_default != True)
367 def get_memory(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
371 context = context.copy()
372 context.update(self._context)
378 ids2 = obj.pool.get(self._obj).search(cr, user, [(self._fields_id, 'in', ids)], limit=self._limit, context=context)
379 for r in obj.pool.get(self._obj).read(cr, user, ids2, [self._fields_id], context=context, load='_classic_write'):
380 if r[self._fields_id] in res:
381 res[r[self._fields_id]].append(r['id'])
384 def set_memory(self, cr, obj, id, field, values, user=None, context=None):
388 context = context.copy()
389 context.update(self._context)
392 obj = obj.pool.get(self._obj)
395 act[2][self._fields_id] = id
396 obj.create(cr, user, act[2], context=context)
398 obj.write(cr, user, [act[1]], act[2], context=context)
400 obj.unlink(cr, user, [act[1]], context=context)
402 obj.datas[act[1]][self._fields_id] = False
404 obj.datas[act[1]] = id
406 for o in obj.datas.values():
407 if o[self._fields_id] == id:
408 o[self._fields_id] = False
410 for id2 in (act[2] or []):
411 obj.datas[id2][self._fields_id] = id
413 def search_memory(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, operator='like', context=None):
414 raise _('Not Implemented')
416 def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
420 context = context.copy()
421 context.update(self._context)
427 ids2 = obj.pool.get(self._obj).search(cr, user, [(self._fields_id, 'in', ids)], limit=self._limit, context=context)
428 for r in obj.pool.get(self._obj)._read_flat(cr, user, ids2, [self._fields_id], context=context, load='_classic_write'):
429 res[r[self._fields_id]].append(r['id'])
432 def set(self, cr, obj, id, field, values, user=None, context=None):
437 context = context.copy()
438 context.update(self._context)
439 context['no_store_function'] = True
442 _table = obj.pool.get(self._obj)._table
443 obj = obj.pool.get(self._obj)
446 act[2][self._fields_id] = id
447 id_new = obj.create(cr, user, act[2], context=context)
448 result += obj._store_get_values(cr, user, [id_new], act[2].keys(), context)
450 obj.write(cr, user, [act[1]], act[2], context=context)
452 obj.unlink(cr, user, [act[1]], context=context)
454 cr.execute('update '+_table+' set '+self._fields_id+'=null where id=%s', (act[1],))
456 cr.execute('update '+_table+' set '+self._fields_id+'=%s where id=%s', (id, act[1]))
458 cr.execute('update '+_table+' set '+self._fields_id+'=null where '+self._fields_id+'=%s', (id,))
460 obj.write(cr, user, act[2], {self._fields_id:id}, context=context or {})
462 cr.execute('select id from '+_table+' where '+self._fields_id+'=%s and id not in ('+','.join(map(str, ids2))+')', (id,))
463 ids3 = map(lambda x:x[0], cr.fetchall())
464 obj.write(cr, user, ids3, {self._fields_id:False}, context=context or {})
467 def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, operator='like'):
468 return obj.pool.get(self._obj).name_search(cr, uid, value, self._domain, offset, limit)
472 # Values: (0, 0, { fields }) create
473 # (1, ID, { fields }) modification
478 # (6, ?, ids) set a list of links
480 class many2many(_column):
481 _classic_read = False
482 _classic_write = False
486 def __init__(self, obj, rel, id1, id2, string='unknown', limit=None, **args):
487 _column.__init__(self, string=string, **args)
490 raise Exception(_('The second argument of the many2many field %s must be a SQL table !'\
491 'You used %s, which is not a valid SQL table name.')% (string,rel))
497 def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
507 ids_s = ','.join(map(str, ids))
508 limit_str = self._limit is not None and ' limit %d' % self._limit or ''
509 obj = obj.pool.get(self._obj)
511 d1, d2 = obj.pool.get('ir.rule').domain_get(cr, user, obj._name)
515 cr.execute('SELECT '+self._rel+'.'+self._id2+','+self._rel+'.'+self._id1+' \
516 FROM '+self._rel+' , '+obj._table+' \
517 WHERE '+self._rel+'.'+self._id1+' in ('+ids_s+') \
518 AND '+self._rel+'.'+self._id2+' = '+obj._table+'.id '+d1
519 +limit_str+' order by '+obj._table+'.'+obj._order+' offset %s',
521 for r in cr.fetchall():
522 res[r[1]].append(r[0])
525 def set(self, cr, obj, id, name, values, user=None, context=None):
530 obj = obj.pool.get(self._obj)
533 idnew = obj.create(cr, user, act[2])
534 cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%s,%s)', (id, idnew))
536 obj.write(cr, user, [act[1]], act[2], context=context)
538 obj.unlink(cr, user, [act[1]], context=context)
540 cr.execute('delete from '+self._rel+' where ' + self._id1 + '=%s and '+ self._id2 + '=%s', (id, act[1]))
542 cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%s,%s)', (id, act[1]))
544 cr.execute('update '+self._rel+' set '+self._id2+'=null where '+self._id2+'=%s', (id,))
547 d1, d2 = obj.pool.get('ir.rule').domain_get(cr, user, obj._name)
550 cr.execute('delete from '+self._rel+' where '+self._id1+'=%s AND '+self._id2+' IN (SELECT '+self._rel+'.'+self._id2+' FROM '+self._rel+', '+obj._table+' WHERE '+self._rel+'.'+self._id1+'=%s AND '+self._rel+'.'+self._id2+' = '+obj._table+'.id '+ d1 +')', [id, id]+d2)
552 for act_nbr in act[2]:
553 cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%s, %s)', (id, act_nbr))
556 # TODO: use a name_search
558 def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, operator='like'):
559 return obj.pool.get(self._obj).search(cr, uid, args+self._domain+[('name', operator, value)], offset, limit)
561 def get_memory(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
564 result[id] = obj.datas[id].get(name, [])
567 def set_memory(self, cr, obj, id, name, values, user=None, context=None):
571 # TODO: use constants instead of these magic numbers
573 raise _('Not Implemented')
575 raise _('Not Implemented')
577 raise _('Not Implemented')
579 raise _('Not Implemented')
581 raise _('Not Implemented')
583 raise _('Not Implemented')
585 obj.datas[id][name] = act[2]
588 # ---------------------------------------------------------
590 # ---------------------------------------------------------
591 class function(_column):
592 _classic_read = False
593 _classic_write = False
599 # multi: compute several fields in one call
601 def __init__(self, fnct, arg=None, fnct_inv=None, fnct_inv_arg=None, type='float', fnct_search=None, obj=None, method=False, store=False, multi=False, **args):
602 _column.__init__(self, **args)
604 self._method = method
606 self._fnct_inv = fnct_inv
609 if 'relation' in args:
610 self._obj = args['relation']
611 self._fnct_inv_arg = fnct_inv_arg
615 self._fnct_search = fnct_search
618 if not fnct_search and not store:
619 self.selectable = False
622 self._classic_read = True
623 self._classic_write = True
625 self._symbol_get=lambda x:x and str(x)
628 self._symbol_c = float._symbol_c
629 self._symbol_f = float._symbol_f
630 self._symbol_set = float._symbol_set
632 def search(self, cr, uid, obj, name, args):
633 if not self._fnct_search:
634 #CHECKME: should raise an exception
636 return self._fnct_search(obj, cr, uid, obj, name, args)
638 def get(self, cr, obj, ids, name, user=None, context=None, values=None):
645 res = self._fnct(obj, cr, user, ids, name, self._arg, context)
647 res = self._fnct(cr, obj._table, ids, name, self._arg, context)
649 if self._type == "many2one" :
650 # Filtering only integer/long values if passed
651 res_ids = [x for x in res.values() if x and isinstance(x, (int,long))]
654 obj_model = obj.pool.get(self._obj)
655 dict_names = dict(obj_model.name_get(cr, user, res_ids, context))
657 if res[r] and res[r] in dict_names:
658 res[r] = (res[r], dict_names[res[r]])
660 if self._type == 'binary' and context.get('bin_size', False):
661 # convert the data returned by the function with the size of that data...
662 res = dict(map(lambda (x, y): (x, tools.human_size(len(y or ''))), res.items()))
666 def set(self, cr, obj, id, name, value, user=None, context=None):
670 self._fnct_inv(obj, cr, user, id, name, value, self._fnct_inv_arg, context)
673 # ---------------------------------------------------------
675 # ---------------------------------------------------------
677 class related(function):
679 def _fnct_search(self, tobj, cr, uid, obj=None, name=None, domain=None, context={}):
680 self._field_get2(cr, uid, obj, context)
684 if type(sarg) in [type([]), type( (1,) )]:
685 where = [(self._arg[i], 'in', sarg)]
687 where = [(self._arg[i], '=', sarg)]
689 where = map(lambda x: (self._arg[i],x[1], x[2]), domain)
691 sarg = obj.pool.get(self._relations[i]['object']).search(cr, uid, where, context=context)
693 return [(self._arg[0], 'in', sarg)]
695 def _fnct_write(self,obj,cr, uid, ids, field_name, values, args, context=None):
696 if values and field_name:
697 self._field_get2(cr, uid, obj, context)
700 if type(ids) != type([]):
702 objlst = obj.browse(cr, uid, ids)
707 for i in range(len(self.arg)):
708 field_detail = self._relations[i]
709 relation = field_detail['object']
710 if not t_data[self.arg[i]]:
713 if field_detail['type'] in ('one2many', 'many2many'):
714 if self._type != "many2one":
716 t_data = t_data[self.arg[i]][0]
719 t_data = t_data[self.arg[i]]
721 obj.pool.get(field_detail['object']).write(cr,uid,[t_id],{args[-1]:values})
723 def _fnct_read(self, obj, cr, uid, ids, field_name, args, context=None):
724 self._field_get2(cr, uid, obj, context)
725 if not ids: return {}
727 res = {}.fromkeys(ids, False)
728 objlst = obj.browse(cr, uid, ids)
734 for i in range(len(self.arg)):
735 field_detail = self._relations[i]
736 relation = field_detail['object']
738 if not t_data[self.arg[i]]:
744 if field_detail['type'] in ('one2many', 'many2many'):
745 t_data = t_data[self.arg[i]][0]
747 t_data = t_data[self.arg[i]]
748 if type(t_data) == type(objlst[0]):
749 res[data.id] = t_data.id
751 res[data.id] = t_data
753 if self._type=='many2one':
754 ids = filter(None, res.values())
756 ng = dict(obj.pool.get(self._obj).name_get(cr, uid, ids, context=context))
759 res[r] = (res[r], ng[res[r]])
762 def __init__(self, *arg, **args):
765 super(related, self).__init__(self._fnct_read, arg, self._fnct_write, fnct_inv_arg=arg, method=True, fnct_search=self._fnct_search, **args)
767 def _field_get2(self, cr, uid, obj, context={}):
771 for i in range(len(self._arg)):
772 f = obj.pool.get(obj_name).fields_get(cr, uid, [self._arg[i]], context=context)[self._arg[i]]
773 self._relations.append({
778 if f.get('relation',False):
779 obj_name = f['relation']
780 self._relations[-1]['relation'] = f['relation']
782 # ---------------------------------------------------------
784 # ---------------------------------------------------------
786 class dummy(function):
787 def _fnct_search(self, tobj, cr, uid, obj=None, name=None, domain=None, context={}):
790 def _fnct_write(self,obj,cr, uid, ids, field_name, values, args, context=None):
793 def _fnct_read(self, obj, cr, uid, ids, field_name, args, context=None):
796 def __init__(self, *arg, **args):
799 super(dummy, self).__init__(self._fnct_read, arg, self._fnct_write, fnct_inv_arg=arg, method=True, fnct_search=None, **args)
801 # ---------------------------------------------------------
803 # ---------------------------------------------------------
804 class serialized(_column):
805 def __init__(self, string='unknown', serialize_func=repr, deserialize_func=eval, type='text', **args):
806 self._serialize_func = serialize_func
807 self._deserialize_func = deserialize_func
809 self._symbol_set = (self._symbol_c, self._serialize_func)
810 self._symbol_get = self._deserialize_func
811 super(serialized, self).__init__(string=string, **args)
814 class property(function):
816 def _fnct_write(self, obj, cr, uid, id, prop, id_val, val, context=None):
820 definition_id = self._field_get(cr, uid, obj._name, prop)
822 property = obj.pool.get('ir.property')
823 nid = property.search(cr, uid, [('fields_id', '=', definition_id),
824 ('res_id', '=', obj._name+','+str(id))])
826 cr.execute('DELETE FROM ir_property WHERE id=%s', (nid.pop(),))
828 nid = property.search(cr, uid, [('fields_id', '=', definition_id),
829 ('res_id', '=', False)])
832 default_val = property.browse(cr, uid, nid[0], context).value
834 company_id = obj.pool.get('res.users').company_get(cr, uid, uid)
836 newval = (id_val and obj_dest+','+str(id_val)) or False
837 if (newval != default_val) and newval:
838 propdef = obj.pool.get('ir.model.fields').browse(cr, uid,
839 definition_id, context=context)
840 res = property.create(cr, uid, {
841 'name': propdef.name,
843 'res_id': obj._name+','+str(id),
844 'company_id': company_id,
845 'fields_id': definition_id
849 def _fnct_read(self, obj, cr, uid, ids, prop, val, context=None):
852 property = obj.pool.get('ir.property')
853 definition_id = self._field_get(cr, uid, obj._name, prop)
855 nid = property.search(cr, uid, [('fields_id', '=', definition_id),
856 ('res_id', '=', False)])
859 d = property.browse(cr, uid, nid[0], context).value
860 default_val = (d and int(d.split(',')[1])) or False
862 vids = [obj._name + ',' + str(id) for id in ids]
863 nids = property.search(cr, uid, [('fields_id', '=', definition_id),
864 ('res_id', 'in', vids)])
868 res[id] = default_val
869 for prop in property.browse(cr, uid, nids):
870 res[int(prop.res_id.split(',')[1])] = (prop.value and \
871 int(prop.value.split(',')[1])) or False
873 obj = obj.pool.get(self._obj)
875 to_check = res.values()
876 if default_val and default_val not in to_check:
877 to_check += [default_val]
878 existing_ids = obj.search(cr, uid, [('id', 'in', to_check)])
880 for id, res_id in res.items():
881 if res_id not in existing_ids:
882 cr.execute('DELETE FROM ir_property WHERE value=%s', ((obj._name+','+str(res_id)),))
883 res[id] = default_val
885 names = dict(obj.name_get(cr, uid, existing_ids, context))
887 if res[r] and res[r] in names:
888 res[r] = (res[r], names[res[r]])
893 def _field_get(self, cr, uid, model_name, prop):
894 if not self.field_id.get(cr.dbname):
895 cr.execute('SELECT id \
896 FROM ir_model_fields \
897 WHERE name=%s AND model=%s', (prop, model_name))
899 self.field_id[cr.dbname] = res and res[0]
900 return self.field_id[cr.dbname]
902 def __init__(self, obj_prop, **args):
904 function.__init__(self, self._fnct_read, False, self._fnct_write,
905 (obj_prop, ), **args)
911 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: