1 # -*- encoding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2008 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
38 from psycopg2 import Binary
44 def _symbol_set(symb):
45 if symb == None or symb == False:
47 elif isinstance(symb, unicode):
48 return symb.encode('utf-8')
52 class _column(object):
60 _symbol_f = _symbol_set
61 _symbol_set = (_symbol_c, _symbol_f)
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 {}
67 self.readonly = readonly
68 self.required = required
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
83 setattr(self, a, args[a])
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))
91 def set_memory(self, cr, obj, id, name, value, user=None, context=None):
92 raise Exception(_('Not implemented set_memory method !'))
94 def get_memory(self, cr, obj, ids, name, user=None, context=None, values=None):
95 raise Exception(_('Not implemented get_memory method !'))
97 def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
98 raise Exception(_('undefined get method !'))
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]
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 !'))
109 # ---------------------------------------------------------
111 # ---------------------------------------------------------
112 class boolean(_column):
115 _symbol_f = lambda x: x and 'True' or 'False'
116 _symbol_set = (_symbol_c, _symbol_f)
119 class integer_big(_column):
120 _type = 'integer_big'
122 _symbol_f = lambda x: int(x or 0)
123 _symbol_set = (_symbol_c, _symbol_f)
125 class integer(_column):
128 _symbol_f = lambda x: int(x or 0)
129 _symbol_set = (_symbol_c, _symbol_f)
132 class reference(_column):
135 def __init__(self, string, selection, size, **args):
136 _column.__init__(self, string=string, size=size, selection=selection, **args)
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)
146 # takes a string (encoded in utf8) and returns a string (encoded in utf8)
147 def _symbol_set_char(self, symb):
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:
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):
162 u_symb = unicode(symb)
163 return u_symb[:self.size].encode('utf8')
171 class float(_column):
174 _symbol_f = lambda x: __builtin__.float(x or 0.0)
175 _symbol_set = (_symbol_c, _symbol_f)
177 def __init__(self, string='unknown', digits=None, **args):
178 _column.__init__(self, string=string, **args)
186 class datetime(_column):
194 class binary(_column):
197 _symbol_f = lambda symb: symb and Binary(symb) or None
198 _symbol_set = (_symbol_c, _symbol_f)
200 _classic_read = False
202 def __init__(self, string='unknown', filters=None, **args):
203 _column.__init__(self, string=string, **args)
204 self.filters = filters
206 def get_memory(self, cr, obj, ids, name, user=None, context=None, values=None):
219 res.setdefault(i, val)
220 if context.get('bin_size', False):
221 res[i] = tools.human_size(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 def __init__(self, obj, string='unknown', **args):
281 _column.__init__(self, string=string, **args)
285 # TODO: speed improvement
287 # name is the name of the relation field
288 def get_memory(self, cr, obj, ids, name, user=None, context=None, values=None):
291 result[id] = obj.datas[id][name]
294 def get(self, cr, obj, ids, name, user=None, context=None, values=None):
301 res[r['id']] = r[name]
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
308 names = dict(obj.name_get(cr, user, filter(None, res.values()), context))
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]
318 if res[r] and res[r] in names:
319 res[r] = (res[r], names[res[r]])
324 def set(self, cr, obj_src, id, field, values, user=None, context=None):
327 obj = obj_src.pool.get(self._obj)
328 self._table = obj_src.pool.get(self._obj)._table
329 if type(values) == type([]):
332 id_new = obj.create(cr, act[2])
333 cr.execute('update '+obj_src._table+' set '+field+'=%s where id=%s', (id_new, id))
335 obj.write(cr, [act[1]], act[2], context=context)
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,))
341 cr.execute('update '+obj_src._table+' set '+field+'=%s where id=%s', (act[1], id))
344 cr.execute('update '+obj_src._table+' set '+field+'=%s where id=%s', (values, id))
346 cr.execute('update '+obj_src._table+' set '+field+'=null where id=%s', (id,))
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)
352 class one2many(_column):
353 _classic_read = False
354 _classic_write = False
357 def __init__(self, obj, fields_id, string='unknown', limit=None, **args):
358 _column.__init__(self, string=string, **args)
360 self._fields_id = fields_id
362 #one2many can't be used as condition for defaults
363 assert(self.change_default != True)
365 def get_memory(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
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'])
379 def set_memory(self, cr, obj, id, field, values, user=None, context=None):
384 obj = obj.pool.get(self._obj)
387 act[2][self._fields_id] = id
388 obj.create(cr, user, act[2], context=context)
390 obj.write(cr, user, [act[1]], act[2], context=context)
392 obj.unlink(cr, user, [act[1]], context=context)
394 obj.datas[act[1]][self._fields_id] = False
396 obj.datas[act[1]] = id
398 for o in obj.datas.values():
399 if o[self._fields_id] == id:
400 o[self._fields_id] = False
402 for id2 in (act[2] or []):
403 obj.datas[id2][self._fields_id] = id
405 def search_memory(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, operator='like', context=None):
406 raise _('Not Implemented')
408 def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
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'])
421 def set(self, cr, obj, id, field, values, user=None, context=None):
426 _table = obj.pool.get(self._obj)._table
427 obj = obj.pool.get(self._obj)
430 act[2][self._fields_id] = id
431 obj.create(cr, user, act[2], context=context)
433 obj.write(cr, user, [act[1]], act[2], context=context)
435 obj.unlink(cr, user, [act[1]], context=context)
437 cr.execute('update '+_table+' set '+self._fields_id+'=null where id=%s', (act[1],))
439 cr.execute('update '+_table+' set '+self._fields_id+'=%s where id=%s', (id, act[1]))
441 cr.execute('update '+_table+' set '+self._fields_id+'=null where '+self._fields_id+'=%s', (id,))
447 cr.execute('update '+_table+' set '+self._fields_id+'=NULL where '+self._fields_id+'=%s and id not in ('+','.join(map(str, ids2))+')', (id,))
449 cr.execute('update '+_table+' set '+self._fields_id+'=%s where id in ('+','.join(map(str, act[2]))+')', (id,))
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)
456 # Values: (0, 0, { fields }) create
457 # (1, ID, { fields }) modification
462 # (6, ?, ids) set a list of links
464 class many2many(_column):
465 _classic_read = False
466 _classic_write = False
469 def __init__(self, obj, rel, id1, id2, string='unknown', limit=None, **args):
470 _column.__init__(self, string=string, **args)
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))
480 def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
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)
494 d1, d2 = obj.pool.get('ir.rule').domain_get(cr, user, obj._name)
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',
504 for r in cr.fetchall():
505 res[r[1]].append(r[0])
508 def set(self, cr, obj, id, name, values, user=None, context=None):
513 obj = obj.pool.get(self._obj)
516 idnew = obj.create(cr, user, act[2])
517 cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%s,%s)', (id, idnew))
519 obj.write(cr, user, [act[1]], act[2], context=context)
521 obj.unlink(cr, user, [act[1]], context=context)
523 cr.execute('delete from '+self._rel+' where ' + self._id1 + '=%s and '+ self._id2 + '=%s', (id, act[1]))
525 cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%s,%s)', (id, act[1]))
527 cr.execute('update '+self._rel+' set '+self._id2+'=null where '+self._id2+'=%s', (id,))
530 d1, d2 = obj.pool.get('ir.rule').domain_get(cr, user, obj._name)
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)
535 for act_nbr in act[2]:
536 cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%s, %s)', (id, act_nbr))
539 # TODO: use a name_search
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)
544 def get_memory(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
547 result[id] = obj.datas[id].get(name, [])
550 def set_memory(self, cr, obj, id, name, values, user=None, context=None):
554 # TODO: use constants instead of these magic numbers
556 raise _('Not Implemented')
558 raise _('Not Implemented')
560 raise _('Not Implemented')
562 raise _('Not Implemented')
564 raise _('Not Implemented')
566 raise _('Not Implemented')
568 obj.datas[id][name] = act[2]
571 # ---------------------------------------------------------
573 # ---------------------------------------------------------
574 class function(_column):
575 _classic_read = False
576 _classic_write = False
581 # multi: compute several fields in one call
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)
586 self._method = method
588 self._fnct_inv = fnct_inv
591 if 'relation' in args:
592 self._obj = args['relation']
593 self._fnct_inv_arg = fnct_inv_arg
597 self._fnct_search = fnct_search
600 self._classic_read = True
601 self._classic_write = True
603 self._symbol_c = float._symbol_c
604 self._symbol_f = float._symbol_f
605 self._symbol_set = float._symbol_set
607 def search(self, cr, uid, obj, name, args):
608 if not self._fnct_search:
609 #CHECKME: should raise an exception
611 return self._fnct_search(obj, cr, uid, obj, name, args)
613 def get(self, cr, obj, ids, name, user=None, context=None, values=None):
620 res = self._fnct(obj, cr, user, ids, name, self._arg, context)
622 res = self._fnct(cr, obj._table, ids, name, self._arg, context)
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()))
629 def set(self, cr, obj, id, name, value, user=None, context=None):
633 self._fnct_inv(obj, cr, user, id, name, value, self._fnct_inv_arg, context)
635 # ---------------------------------------------------------
637 # ---------------------------------------------------------
639 class related(function):
641 def _fnct_search(self, tobj, cr, uid, obj=None, name=None, domain=None, context={}):
642 self._field_get2(cr, uid, obj, context)
646 if type(sarg) in [type([]), type( (1,) )]:
647 where = [(self._arg[i], 'in', sarg)]
649 where = [(self._arg[i], '=', sarg)]
651 where = map(lambda x: (self._arg[i],x[1], x[2]), domain)
653 sarg = obj.pool.get(self._relations[i]['object']).search(cr, uid, where, context=context)
655 return [(self._arg[0], 'in', sarg)]
657 def _fnct_write(self,obj,cr, uid, ids,values, field_name, args, context=None):
658 raise 'Not Implemented Yet'
660 def _fnct_read(self, obj, cr, uid, ids, field_name, args, context=None):
661 self._field_get2(cr, uid, obj, context)
662 if not ids: return {}
665 objlst = obj.browse(cr, uid, ids)
669 for i in range(len(self.arg)):
670 field_detail = self._relations[i]
671 relation = field_detail['object']
672 if not t_data[self.arg[i]]:
675 if field_detail['type'] in ('one2many', 'many2many'):
676 t_data = t_data[self.arg[i]][0]
678 t_data = t_data[self.arg[i]]
679 if type(t_data) == type(objlst[0]):
680 res[data.id] = (t_data.id,t_data.name)
682 res[data.id] = t_data
685 def __init__(self, *arg, **args):
688 super(related, self).__init__(self._fnct_read, arg, fnct_inv_arg=arg, method=True, fnct_search=self._fnct_search, **args)
690 def _field_get2(self, cr, uid, obj, context={}):
694 for i in range(len(self._arg)):
695 f = obj.pool.get(obj_name).fields_get(cr, uid, [self._arg[i]], context=context)[self._arg[i]]
696 self._relations.append({
701 if f.get('relation',False):
702 obj_name = f['relation']
703 self._relations[-1]['relation'] = f['relation']
705 # ---------------------------------------------------------
707 # ---------------------------------------------------------
708 class serialized(_column):
709 def __init__(self, string='unknown', serialize_func=repr, deserialize_func=eval, type='text', **args):
710 self._serialize_func = serialize_func
711 self._deserialize_func = deserialize_func
713 self._symbol_set = (self._symbol_c, self._serialize_func)
714 self._symbol_get = self._deserialize_func
715 super(serialized, self).__init__(string=string, **args)
718 class property(function):
720 def _fnct_write(self, obj, cr, uid, id, prop, id_val, val, context=None):
724 definition_id = self._field_get(cr, uid, obj._name, prop)
726 property = obj.pool.get('ir.property')
727 nid = property.search(cr, uid, [('fields_id', '=', definition_id),
728 ('res_id', '=', obj._name+','+str(id))])
730 cr.execute('DELETE FROM ir_property WHERE id=%s', (nid.pop(),))
732 nid = property.search(cr, uid, [('fields_id', '=', definition_id),
733 ('res_id', '=', False)])
736 default_val = property.browse(cr, uid, nid[0], context).value
738 company_id = obj.pool.get('res.users').company_get(cr, uid, uid)
740 newval = (id_val and obj_dest+','+str(id_val)) or False
741 if (newval != default_val) and newval:
742 propdef = obj.pool.get('ir.model.fields').browse(cr, uid,
743 definition_id, context=context)
744 res = property.create(cr, uid, {
745 'name': propdef.name,
747 'res_id': obj._name+','+str(id),
748 'company_id': company_id,
749 'fields_id': definition_id
753 def _fnct_read(self, obj, cr, uid, ids, prop, val, context=None):
756 property = obj.pool.get('ir.property')
757 definition_id = self._field_get(cr, uid, obj._name, prop)
759 nid = property.search(cr, uid, [('fields_id', '=', definition_id),
760 ('res_id', '=', False)])
763 d = property.browse(cr, uid, nid[0], context).value
764 default_val = (d and int(d.split(',')[1])) or False
766 vids = [obj._name + ',' + str(id) for id in ids]
767 nids = property.search(cr, uid, [('fields_id', '=', definition_id),
768 ('res_id', 'in', vids)])
772 res[id] = default_val
773 for prop in property.browse(cr, uid, nids):
774 res[int(prop.res_id.split(',')[1])] = (prop.value and \
775 int(prop.value.split(',')[1])) or False
777 obj = obj.pool.get(self._obj)
778 names = dict(obj.name_get(cr, uid, filter(None, res.values()), context))
780 if res[r] and res[r] in names:
781 res[r] = (res[r], names[res[r]])
786 def _field_get(self, cr, uid, model_name, prop):
787 if not self.field_id.get(cr.dbname):
788 cr.execute('SELECT id \
789 FROM ir_model_fields \
790 WHERE name=%s AND model=%s', (prop, model_name))
792 self.field_id[cr.dbname] = res and res[0]
793 return self.field_id[cr.dbname]
795 def __init__(self, obj_prop, **args):
797 function.__init__(self, self._fnct_read, False, self._fnct_write,
798 (obj_prop, ), **args)
804 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: