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
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=%d', (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.encode('utf8')[:self.size]
172 class float(_column):
175 _symbol_f = lambda x: __builtin__.float(x or 0.0)
176 _symbol_set = (_symbol_c, _symbol_f)
178 def __init__(self, string='unknown', digits=None, **args):
179 _column.__init__(self, string=string, **args)
187 class datetime(_column):
195 class binary(_column):
198 _symbol_f = lambda symb: symb and psycopg.Binary(symb) or None
199 _symbol_set = (_symbol_c, _symbol_f)
201 _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):
220 res.setdefault(i, val)
221 if context.get('bin_size', False):
222 res[i] = tools.human_size(val)
229 class selection(_column):
232 def __init__(self, selection, string='unknown', **args):
233 _column.__init__(self, string=string, **args)
234 self.selection = selection
236 # ---------------------------------------------------------
238 # ---------------------------------------------------------
241 # Values: (0, 0, { fields }) create
242 # (1, ID, { fields }) modification
243 # (2, ID) remove (delete)
244 # (3, ID) unlink one (target id or target of relation)
246 # (5) unlink all (only valid for one2many)
248 #CHECKME: dans la pratique c'est quoi la syntaxe utilisee pour le 5? (5) ou (5, 0)?
249 class one2one(_column):
250 _classic_read = False
251 _classic_write = True
254 def __init__(self, obj, string='unknown', **args):
255 warnings.warn("The one2one field doesn't work anymore", DeprecationWarning)
256 _column.__init__(self, string=string, **args)
259 def set(self, cr, obj_src, id, field, act, user=None, context=None):
262 obj = obj_src.pool.get(self._obj)
263 self._table = obj_src.pool.get(self._obj)._table
265 id_new = obj.create(cr, user, act[1])
266 cr.execute('update '+obj_src._table+' set '+field+'=%d where id=%d', (id_new, id))
268 cr.execute('select '+field+' from '+obj_src._table+' where id=%d', (act[0],))
269 id = cr.fetchone()[0]
270 obj.write(cr, user, [id], act[1], context=context)
272 def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None):
273 return obj.pool.get(self._obj).search(cr, uid, args+self._domain+[('name', 'like', value)], offset, limit)
276 class many2one(_column):
277 _classic_read = False
278 _classic_write = True
281 def __init__(self, obj, string='unknown', **args):
282 _column.__init__(self, string=string, **args)
286 # TODO: speed improvement
288 # name is the name of the relation field
289 def get_memory(self, cr, obj, ids, name, user=None, context=None, values=None):
292 result[id] = obj.datas[id][name]
295 def get(self, cr, obj, ids, name, user=None, context=None, values=None):
302 res[r['id']] = r[name]
304 res.setdefault(id, '')
305 obj = obj.pool.get(self._obj)
306 # build a dictionary of the form {'id_of_distant_resource': name_of_distant_resource}
307 from orm import except_orm
309 names = dict(obj.name_get(cr, user, filter(None, res.values()), context))
313 iids = filter(None, res.values())
314 cr.execute('select id,'+obj._rec_name+' from '+obj._table+' where id in ('+','.join(map(str, iids))+')')
315 for res22 in cr.fetchall():
316 names[res22[0]] = res22[1]
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+'=%d where id=%d', (id_new, id))
336 obj.write(cr, [act[1]], act[2], context=context)
338 cr.execute('delete from '+self._table+' where id=%d', (act[1],))
339 elif act[0] == 3 or act[0] == 5:
340 cr.execute('update '+obj_src._table+' set '+field+'=null where id=%d', (id,))
342 cr.execute('update '+obj_src._table+' set '+field+'=%d where id=%d', (act[1], id))
345 cr.execute('update '+obj_src._table+' set '+field+'=%d where id=%d', (values, id))
347 cr.execute('update '+obj_src._table+' set '+field+'=null where id=%d', (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
358 def __init__(self, obj, fields_id, string='unknown', limit=None, **args):
359 _column.__init__(self, string=string, **args)
361 self._fields_id = fields_id
363 #one2many can't be used as condition for defaults
364 assert(self.change_default != True)
366 def get_memory(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
374 ids2 = obj.pool.get(self._obj).search(cr, user, [(self._fields_id, 'in', ids)], limit=self._limit)
375 for r in obj.pool.get(self._obj).read(cr, user, ids2, [self._fields_id], context=context, load='_classic_write'):
376 if r[self._fields_id] in res:
377 res[r[self._fields_id]].append(r['id'])
380 def set_memory(self, cr, obj, id, field, values, user=None, context=None):
385 obj = obj.pool.get(self._obj)
388 act[2][self._fields_id] = id
389 obj.create(cr, user, act[2], context=context)
391 obj.write(cr, user, [act[1]], act[2], context=context)
393 obj.unlink(cr, user, [act[1]], context=context)
395 obj.datas[act[1]][self._fields_id] = False
397 obj.datas[act[1]] = id
399 for o in obj.datas.values():
400 if o[self._fields_id] == id:
401 o[self._fields_id] = False
403 for id2 in (act[2] or []):
404 obj.datas[id2][self._fields_id] = id
406 def search_memory(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, operator='like', context=None):
407 raise _('Not Implemented')
409 def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
417 ids2 = obj.pool.get(self._obj).search(cr, user, [(self._fields_id, 'in', ids)], limit=self._limit)
418 for r in obj.pool.get(self._obj)._read_flat(cr, user, ids2, [self._fields_id], context=context, load='_classic_write'):
419 res[r[self._fields_id]].append(r['id'])
422 def set(self, cr, obj, id, field, values, user=None, context=None):
427 _table = obj.pool.get(self._obj)._table
428 obj = obj.pool.get(self._obj)
431 act[2][self._fields_id] = id
432 print 'CREATE', self._obj, act[2], context
433 obj.create(cr, user, act[2], context=context)
435 obj.write(cr, user, [act[1]], act[2], context=context)
437 obj.unlink(cr, user, [act[1]], context=context)
439 cr.execute('update '+_table+' set '+self._fields_id+'=null where id=%d', (act[1],))
441 cr.execute('update '+_table+' set '+self._fields_id+'=%d where id=%d', (id, act[1]))
443 cr.execute('update '+_table+' set '+self._fields_id+'=null where '+self._fields_id+'=%d', (id,))
449 cr.execute('update '+_table+' set '+self._fields_id+'=NULL where '+self._fields_id+'=%d and id not in ('+','.join(map(str, ids2))+')', (id,))
451 cr.execute('update '+_table+' set '+self._fields_id+'=%d where id in ('+','.join(map(str, act[2]))+')', (id,))
453 def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, operator='like'):
454 return obj.pool.get(self._obj).name_search(cr, uid, value, self._domain, offset, limit)
458 # Values: (0, 0, { fields }) create
459 # (1, ID, { fields }) modification
464 # (6, ?, ids) set a list of links
466 class many2many(_column):
467 _classic_read = False
468 _classic_write = False
471 def __init__(self, obj, rel, id1, id2, string='unknown', limit=None, **args):
472 _column.__init__(self, string=string, **args)
475 raise Exception(_('The second argument of the many2many field %s must be a SQL table !'\
476 'You used %s, which is not a valid SQL table name.')% (string,rel))
482 def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
492 ids_s = ','.join(map(str, ids))
493 limit_str = self._limit is not None and ' limit %d' % self._limit or ''
494 obj = obj.pool.get(self._obj)
496 d1, d2 = obj.pool.get('ir.rule').domain_get(cr, user, obj._name)
500 cr.execute('SELECT '+self._rel+'.'+self._id2+','+self._rel+'.'+self._id1+' \
501 FROM '+self._rel+' , '+obj._table+' \
502 WHERE '+self._rel+'.'+self._id1+' in ('+ids_s+') \
503 AND '+self._rel+'.'+self._id2+' = '+obj._table+'.id '+d1
504 +limit_str+' order by '+obj._table+'.'+obj._order+' offset %d',
506 for r in cr.fetchall():
507 res[r[1]].append(r[0])
510 def set(self, cr, obj, id, name, values, user=None, context=None):
515 obj = obj.pool.get(self._obj)
518 idnew = obj.create(cr, user, act[2])
519 cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%d,%d)', (id, idnew))
521 obj.write(cr, user, [act[1]], act[2], context=context)
523 obj.unlink(cr, user, [act[1]], context=context)
525 cr.execute('delete from '+self._rel+' where ' + self._id1 + '=%d and '+ self._id2 + '=%d', (id, act[1]))
527 cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%d,%d)', (id, act[1]))
529 cr.execute('update '+self._rel+' set '+self._id2+'=null where '+self._id2+'=%d', (id,))
532 d1, d2 = obj.pool.get('ir.rule').domain_get(cr, user, obj._name)
535 cr.execute('delete from '+self._rel+' where '+self._id1+'=%d AND '+self._id2+' IN (SELECT '+self._rel+'.'+self._id2+' FROM '+self._rel+', '+obj._table+' WHERE '+self._rel+'.'+self._id1+'=%d AND '+self._rel+'.'+self._id2+' = '+obj._table+'.id '+ d1 +')', [id, id]+d2)
537 for act_nbr in act[2]:
538 cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%d, %d)', (id, act_nbr))
541 # TODO: use a name_search
543 def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, operator='like'):
544 return obj.pool.get(self._obj).search(cr, uid, args+self._domain+[('name', operator, value)], offset, limit)
546 def get_memory(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
549 result[id] = obj.datas[id].get(name, [])
552 def set_memory(self, cr, obj, id, name, values, user=None, context=None):
556 # TODO: use constants instead of these magic numbers
558 raise _('Not Implemented')
560 raise _('Not Implemented')
562 raise _('Not Implemented')
564 raise _('Not Implemented')
566 raise _('Not Implemented')
568 raise _('Not Implemented')
570 obj.datas[id][name] = act[2]
573 # ---------------------------------------------------------
575 # ---------------------------------------------------------
576 class function(_column):
577 _classic_read = False
578 _classic_write = False
583 # multi: compute several fields in one call
585 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):
586 _column.__init__(self, **args)
588 self._method = method
590 self._fnct_inv = fnct_inv
593 if 'relation' in args:
594 self._obj = args['relation']
595 self._fnct_inv_arg = fnct_inv_arg
599 self._fnct_search = fnct_search
602 self._symbol_c = '%f'
603 self._symbol_f = lambda x: __builtin__.float(x or 0.0)
604 self._symbol_set = (self._symbol_c, self._symbol_f)
606 def search(self, cr, uid, obj, name, args):
607 if not self._fnct_search:
608 #CHECKME: should raise an exception
610 return self._fnct_search(obj, cr, uid, obj, name, args)
612 def get(self, cr, obj, ids, name, user=None, context=None, values=None):
619 res = self._fnct(obj, cr, user, ids, name, self._arg, context)
621 res = self._fnct(cr, obj._table, ids, name, self._arg, context)
623 if self._type == 'binary' and context.get('bin_size', False):
624 # convert the data returned by the function with the size of that data...
625 res = dict(map(lambda (x, y): (x, tools.human_size(len(y))), res.items()))
628 def set(self, cr, obj, id, name, value, user=None, context=None):
632 self._fnct_inv(obj, cr, user, id, name, value, self._fnct_inv_arg, context)
634 # ---------------------------------------------------------
636 # ---------------------------------------------------------
638 class related(function):
640 def _fnct_search(self, tobj, cr, uid, obj=None, name=None, context=None):
643 query = "select %s.id from %s" % (obj._table, obj._table)
644 relation_child = obj._name
646 for i in range(len(self._arg)):
647 field_detail = self._field_get(cr, uid, obj, relation, self._arg[i])
648 relation = field_detail[0]
649 if field_detail[1] in ('one2many', 'many2many'):
650 obj_child = obj.pool.get(field_detail[2][self._arg[i]]['relation'])
651 field_detail_child = obj_child.fields_get(cr, uid,)
653 fields_filter = dict(filter(lambda x: x[1].get('relation', False)
654 and x[1].get('relation') == relation_child
655 and x[1].get('type')=='many2one', field_detail_child.items()))
656 query += " inner join %s on %s.id = %s.%s" % (obj_child._table, obj._table, obj_child._table, fields_filter.keys()[0])
657 relation_child = relation
658 elif field_detail[1] in ('many2one'):
659 obj_child = obj.pool.get(field_detail[2][self._arg[i]]['relation'])
660 obj_child2 = obj.pool.get(relation_child)
661 if obj_child._name == obj_child2._name:
662 # 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');
663 # where +=" %s.id = %s.%s in (select id from %s where %s.%s %s %s"%(obj_child._table,obj_child2._table,self._arg[i])
666 query += " inner join %s on %s.id = %s.%s" % (obj_child._table, obj_child._table, obj_child2._table, self._arg[i])
667 relation_child = field_detail[0]
668 if i == (len(self._arg)-1):
669 if obj_child._inherits:
670 obj_child_inherits = obj.pool.get(obj_child._inherits.keys()[0])
671 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])
672 obj_child = obj_child_inherits
673 where += " %s.%s %s '%%%s%%' and" % (obj_child._table, obj_child._rec_name, context[0][1], context[0][2])
675 obj_child = obj.pool.get(relation_child)
676 if field_detail[1] in ('char'):
677 where += " %s.%s %s '%%%s%%' and" % (obj_child._table, self._arg[i], context[0][1], context[0][2])
678 if field_detail[1] in ('date'):
679 where += " %s.%s %s '%s' and" % (obj_child._table, self._arg[i], context[0][1], context[0][2])
680 if field_detail[1] in ['integer', 'long', 'float','integer_big']:
681 where += " %s.%s %s '%d' and" % (obj_child._table, self._arg[i], context[0][1], context[0][2])
682 query += where.rstrip('and')
685 for id in cr.fetchall():
687 return [('id', 'in', ids)]
689 # def _fnct_write(self,obj,cr, uid, ids,values, field_name, args, context=None):
690 # raise 'Not Implemented Yet'
692 def _fnct_read(self, obj, cr, uid, ids, field_name, args, context=None):
693 if not ids: return {}
696 objlst = obj.browse(cr, uid, ids)
700 for i in range(len(self.arg)):
701 field_detail = self._field_get(cr, uid, obj, relation, self.arg[i])
702 relation = field_detail[0]
703 if not t_data[self.arg[i]]:
706 if field_detail[1] in ('one2many', 'many2many'):
707 t_data = t_data[self.arg[i]][0]
709 t_data = t_data[self.arg[i]]
710 if type(t_data) == type(objlst[0]):
711 res[data.id] = t_data.id
713 res[data.id] = t_data
716 def __init__(self, *arg, **args):
718 super(related, self).__init__(self._fnct_read, arg, fnct_inv_arg=arg, method=True, fnct_search=self._fnct_search, **args)
720 # TODO: call field_get on the object, not in the DB
721 def _field_get(self, cr, uid, obj, model_name, prop):
722 fields = obj.pool.get(model_name).fields_get(cr, uid,)
723 if fields.get(prop, False):
724 return(fields[prop].get('relation', False), fields[prop].get('type', False), fields)
726 raise 'Field %s not exist in %s' % (prop, model_name)
729 # ---------------------------------------------------------
731 # ---------------------------------------------------------
732 class serialized(_column):
733 def __init__(self, string='unknown', serialize_func=repr, deserialize_func=eval, type='text', **args):
734 self._serialize_func = serialize_func
735 self._deserialize_func = deserialize_func
737 self._symbol_set = (self._symbol_c, self._serialize_func)
738 self._symbol_get = self._deserialize_func
739 super(serialized, self).__init__(string=string, **args)
742 class property(function):
744 def _fnct_write(self, obj, cr, uid, id, prop, id_val, val, context=None):
748 definition_id = self._field_get(cr, uid, obj._name, prop)
750 property = obj.pool.get('ir.property')
751 nid = property.search(cr, uid, [('fields_id', '=', definition_id),
752 ('res_id', '=', obj._name+','+str(id))])
754 cr.execute('DELETE FROM ir_property WHERE id=%d', (nid.pop(),))
756 nid = property.search(cr, uid, [('fields_id', '=', definition_id),
757 ('res_id', '=', False)])
760 default_val = property.browse(cr, uid, nid[0], context).value
762 company_id = obj.pool.get('res.users').company_get(cr, uid, uid)
764 newval = (id_val and obj_dest+','+str(id_val)) or False
765 if (newval != default_val) and newval:
766 propdef = obj.pool.get('ir.model.fields').browse(cr, uid,
767 definition_id, context=context)
768 res = property.create(cr, uid, {
769 'name': propdef.name,
771 'res_id': obj._name+','+str(id),
772 'company_id': company_id,
773 'fields_id': definition_id
777 def _fnct_read(self, obj, cr, uid, ids, prop, val, context=None):
780 property = obj.pool.get('ir.property')
781 definition_id = self._field_get(cr, uid, obj._name, prop)
783 nid = property.search(cr, uid, [('fields_id', '=', definition_id),
784 ('res_id', '=', False)])
787 d = property.browse(cr, uid, nid[0], context).value
788 default_val = (d and int(d.split(',')[1])) or False
790 vids = [obj._name + ',' + str(id) for id in ids]
791 nids = property.search(cr, uid, [('fields_id', '=', definition_id),
792 ('res_id', 'in', vids)])
796 res[id] = default_val
797 for prop in property.browse(cr, uid, nids):
798 res[int(prop.res_id.split(',')[1])] = (prop.value and \
799 int(prop.value.split(',')[1])) or False
801 obj = obj.pool.get(self._obj)
802 names = dict(obj.name_get(cr, uid, filter(None, res.values()), context))
804 if res[r] and res[r] in names:
805 res[r] = (res[r], names[res[r]])
810 def _field_get(self, cr, uid, model_name, prop):
811 if not self.field_id.get(cr.dbname):
812 cr.execute('SELECT id \
813 FROM ir_model_fields \
814 WHERE name=%s AND model=%s', (prop, model_name))
816 self.field_id[cr.dbname] = res and res[0]
817 return self.field_id[cr.dbname]
819 def __init__(self, obj_prop, **args):
821 function.__init__(self, self._fnct_read, False, self._fnct_write,
822 (obj_prop, ), **args)
828 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: