1 # -*- encoding: utf-8 -*-
2 ##############################################################################
4 # Copyright (c) 2004-2008 TINY SPRL. (http://tiny.be) All Rights Reserved.
8 # WARNING: This program as such is intended to be used by professional
9 # programmers who take the whole responsability of assessing all potential
10 # consequences resulting from its eventual inadequacies and bugs
11 # End users who are looking for a ready-to-use solution with commercial
12 # garantees and support are strongly adviced to contract a Free Software
15 # This program is Free Software; you can redistribute it and/or
16 # modify it under the terms of the GNU General Public License
17 # as published by the Free Software Foundation; either version 2
18 # of the License, or (at your option) any later version.
20 # This program is distributed in the hope that it will be useful,
21 # but WITHOUT ANY WARRANTY; without even the implied warranty of
22 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 # GNU General Public License for more details.
25 # You should have received a copy of the GNU General Public License
26 # along with this program; if not, write to the Free Software
27 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
29 ##############################################################################
33 # - relations (one2many, many2one, many2many)
37 # _classic_read: is a classic sql fields
52 def _symbol_set(symb):
53 if symb == None or symb == False:
55 elif isinstance(symb, unicode):
56 return symb.encode('utf-8')
60 class _column(object):
68 _symbol_f = _symbol_set
69 _symbol_set = (_symbol_c, _symbol_f)
72 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):
73 self.states = states or {}
75 self.readonly = readonly
76 self.required = required
78 self.help = args.get('help', '')
79 self.priority = priority
80 self.change_default = change_default
81 self.ondelete = ondelete
82 self.translate = translate
83 self._domain = domain or []
84 self._context = context
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=%d', (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):
109 ids = obj.search(cr, uid, args+self._domain+[(name, 'ilike', value)], offset, limit)
110 res = obj.read(cr, uid, ids, [name])
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)
127 class integer_big(_column):
128 _type = 'integer_big'
130 _symbol_f = lambda x: int(x or 0)
131 _symbol_set = (_symbol_c, _symbol_f)
133 class integer(_column):
136 _symbol_f = lambda x: int(x or 0)
137 _symbol_set = (_symbol_c, _symbol_f)
140 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 if isinstance(symb, str):
166 u_symb = unicode(symb, 'utf8')
167 elif isinstance(symb, unicode):
170 u_symb = unicode(symb)
171 return u_symb.encode('utf8')[:self.size]
180 class float(_column):
183 _symbol_f = lambda x: __builtin__.float(x or 0.0)
184 _symbol_set = (_symbol_c, _symbol_f)
186 def __init__(self, string='unknown', digits=None, **args):
187 _column.__init__(self, string=string, **args)
195 class datetime(_column):
203 class binary(_column):
206 _symbol_f = lambda symb: symb and psycopg.Binary(symb) or None
207 _symbol_set = (_symbol_c, _symbol_f)
209 _classic_read = False
211 def __init__(self, string='unknown', filters=None, **args):
212 _column.__init__(self, string=string, **args)
213 self.filters = filters
215 def get_memory(self, cr, obj, ids, name, user=None, context=None, values=None):
228 res.setdefault(i, val)
229 if context.get('bin_size', False):
230 res[i] = tools.human_size(val)
237 class selection(_column):
240 def __init__(self, selection, string='unknown', **args):
241 _column.__init__(self, string=string, **args)
242 self.selection = selection
244 # ---------------------------------------------------------
246 # ---------------------------------------------------------
249 # Values: (0, 0, { fields }) create
250 # (1, ID, { fields }) modification
251 # (2, ID) remove (delete)
252 # (3, ID) unlink one (target id or target of relation)
254 # (5) unlink all (only valid for one2many)
256 #CHECKME: dans la pratique c'est quoi la syntaxe utilisee pour le 5? (5) ou (5, 0)?
257 class one2one(_column):
258 _classic_read = False
259 _classic_write = True
262 def __init__(self, obj, string='unknown', **args):
263 warnings.warn("The one2one field doesn't work anymore", DeprecationWarning)
264 _column.__init__(self, string=string, **args)
267 def set(self, cr, obj_src, id, field, act, user=None, context=None):
270 obj = obj_src.pool.get(self._obj)
271 self._table = obj_src.pool.get(self._obj)._table
273 id_new = obj.create(cr, user, act[1])
274 cr.execute('update '+obj_src._table+' set '+field+'=%d where id=%d', (id_new, id))
276 cr.execute('select '+field+' from '+obj_src._table+' where id=%d', (act[0],))
277 id = cr.fetchone()[0]
278 obj.write(cr, user, [id], act[1], context=context)
280 def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None):
281 return obj.pool.get(self._obj).search(cr, uid, args+self._domain+[('name', 'like', value)], offset, limit)
284 class many2one(_column):
285 _classic_read = False
286 _classic_write = True
289 def __init__(self, obj, string='unknown', **args):
290 _column.__init__(self, string=string, **args)
294 # TODO: speed improvement
296 # name is the name of the relation field
297 def get_memory(self, cr, obj, ids, name, user=None, context=None, values=None):
300 result[id] = obj.datas[id][name]
303 def get(self, cr, obj, ids, name, user=None, context=None, values=None):
310 res[r['id']] = r[name]
312 res.setdefault(id, '')
313 obj = obj.pool.get(self._obj)
314 # build a dictionary of the form {'id_of_distant_resource': name_of_distant_resource}
315 from orm import except_orm
317 names = dict(obj.name_get(cr, user, filter(None, res.values()), context))
321 iids = filter(None, res.values())
322 cr.execute('select id,'+obj._rec_name+' from '+obj._table+' where id in ('+','.join(map(str, iids))+')')
323 for res22 in cr.fetchall():
324 names[res22[0]] = res22[1]
327 if res[r] and res[r] in names:
328 res[r] = (res[r], names[res[r]])
333 def set(self, cr, obj_src, id, field, values, user=None, context=None):
336 obj = obj_src.pool.get(self._obj)
337 self._table = obj_src.pool.get(self._obj)._table
338 if type(values) == type([]):
341 id_new = obj.create(cr, act[2])
342 cr.execute('update '+obj_src._table+' set '+field+'=%d where id=%d', (id_new, id))
344 obj.write(cr, [act[1]], act[2], context=context)
346 cr.execute('delete from '+self._table+' where id=%d', (act[1],))
347 elif act[0] == 3 or act[0] == 5:
348 cr.execute('update '+obj_src._table+' set '+field+'=null where id=%d', (id,))
350 cr.execute('update '+obj_src._table+' set '+field+'=%d where id=%d', (act[1], id))
353 cr.execute('update '+obj_src._table+' set '+field+'=%d where id=%d', (values, id))
355 cr.execute('update '+obj_src._table+' set '+field+'=null where id=%d', (id,))
357 def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None):
358 return obj.pool.get(self._obj).search(cr, uid, args+self._domain+[('name', 'like', value)], offset, limit)
361 class one2many(_column):
362 _classic_read = False
363 _classic_write = False
366 def __init__(self, obj, fields_id, string='unknown', limit=None, **args):
367 _column.__init__(self, string=string, **args)
369 self._fields_id = fields_id
371 #one2many can't be used as condition for defaults
372 assert(self.change_default != True)
374 def get_memory(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
382 ids2 = obj.pool.get(self._obj).search(cr, user, [(self._fields_id, 'in', ids)], limit=self._limit)
383 for r in obj.pool.get(self._obj).read(cr, user, ids2, [self._fields_id], context=context, load='_classic_write'):
384 if r[self._fields_id] in res:
385 res[r[self._fields_id]].append(r['id'])
388 def set_memory(self, cr, obj, id, field, values, user=None, context=None):
393 obj = obj.pool.get(self._obj)
396 act[2][self._fields_id] = id
397 obj.create(cr, user, act[2], context=context)
399 obj.write(cr, user, [act[1]], act[2], context=context)
401 obj.unlink(cr, user, [act[1]], context=context)
403 obj.datas[act[1]][self._fields_id] = False
405 obj.datas[act[1]] = id
407 for o in obj.datas.values():
408 if o[self._fields_id] == id:
409 o[self._fields_id] = False
411 for id2 in (act[2] or []):
412 obj.datas[id2][self._fields_id] = id
414 def search_memory(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, operator='like', context=None):
415 raise _('Not Implemented')
417 def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
425 ids2 = obj.pool.get(self._obj).search(cr, user, [(self._fields_id, 'in', ids)], limit=self._limit)
426 for r in obj.pool.get(self._obj)._read_flat(cr, user, ids2, [self._fields_id], context=context, load='_classic_write'):
427 res[r[self._fields_id]].append(r['id'])
430 def set(self, cr, obj, id, field, values, user=None, context=None):
435 _table = obj.pool.get(self._obj)._table
436 obj = obj.pool.get(self._obj)
439 act[2][self._fields_id] = id
440 obj.create(cr, user, act[2], context=context)
442 obj.write(cr, user, [act[1]], act[2], context=context)
444 obj.unlink(cr, user, [act[1]], context=context)
446 cr.execute('update '+_table+' set '+self._fields_id+'=null where id=%d', (act[1],))
448 cr.execute('update '+_table+' set '+self._fields_id+'=%d where id=%d', (id, act[1]))
450 cr.execute('update '+_table+' set '+self._fields_id+'=null where '+self._fields_id+'=%d', (id,))
456 cr.execute('update '+_table+' set '+self._fields_id+'=NULL where '+self._fields_id+'=%d and id not in ('+','.join(map(str, ids2))+')', (id,))
458 cr.execute('update '+_table+' set '+self._fields_id+'=%d where id in ('+','.join(map(str, act[2]))+')', (id,))
460 def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, operator='like'):
461 return obj.pool.get(self._obj).name_search(cr, uid, value, self._domain, offset, limit)
465 # Values: (0, 0, { fields }) create
466 # (1, ID, { fields }) modification
471 # (6, ?, ids) set a list of links
473 class many2many(_column):
474 _classic_read = False
475 _classic_write = False
478 def __init__(self, obj, rel, id1, id2, string='unknown', limit=None, **args):
479 _column.__init__(self, string=string, **args)
482 raise Exception(_('The second argument of the many2many field %s must be a SQL table !'\
483 'You used %s, which is not a valid SQL table name.')% (string,rel))
489 def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
499 ids_s = ','.join(map(str, ids))
500 limit_str = self._limit is not None and ' limit %d' % self._limit or ''
501 obj = obj.pool.get(self._obj)
503 d1, d2 = obj.pool.get('ir.rule').domain_get(cr, user, obj._name)
507 cr.execute('SELECT '+self._rel+'.'+self._id2+','+self._rel+'.'+self._id1+' \
508 FROM '+self._rel+' , '+obj._table+' \
509 WHERE '+self._rel+'.'+self._id1+' in ('+ids_s+') \
510 AND '+self._rel+'.'+self._id2+' = '+obj._table+'.id '+d1
511 +limit_str+' order by '+obj._table+'.'+obj._order+' offset %d',
513 for r in cr.fetchall():
514 res[r[1]].append(r[0])
517 def set(self, cr, obj, id, name, values, user=None, context=None):
522 obj = obj.pool.get(self._obj)
525 idnew = obj.create(cr, user, act[2])
526 cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%d,%d)', (id, idnew))
528 obj.write(cr, user, [act[1]], act[2], context=context)
530 obj.unlink(cr, user, [act[1]], context=context)
532 cr.execute('delete from '+self._rel+' where ' + self._id1 + '=%d and '+ self._id2 + '=%d', (id, act[1]))
534 cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%d,%d)', (id, act[1]))
536 cr.execute('update '+self._rel+' set '+self._id2+'=null where '+self._id2+'=%d', (id,))
539 d1, d2 = obj.pool.get('ir.rule').domain_get(cr, user, obj._name)
542 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)
544 for act_nbr in act[2]:
545 cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%d, %d)', (id, act_nbr))
548 # TODO: use a name_search
550 def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, operator='like'):
551 return obj.pool.get(self._obj).search(cr, uid, args+self._domain+[('name', operator, value)], offset, limit)
553 def get_memory(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
556 result[id] = obj.datas[id].get(name, [])
559 def set_memory(self, cr, obj, id, name, values, user=None, context=None):
563 # TODO: use constants instead of these magic numbers
565 raise _('Not Implemented')
567 raise _('Not Implemented')
569 raise _('Not Implemented')
571 raise _('Not Implemented')
573 raise _('Not Implemented')
575 raise _('Not Implemented')
577 obj.datas[id][name] = act[2]
580 # ---------------------------------------------------------
582 # ---------------------------------------------------------
583 class function(_column):
584 _classic_read = False
585 _classic_write = False
590 # multi: compute several fields in one call
592 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):
593 _column.__init__(self, **args)
595 self._method = method
597 self._fnct_inv = fnct_inv
600 if 'relation' in args:
601 self._obj = args['relation']
602 self._fnct_inv_arg = fnct_inv_arg
606 self._fnct_search = fnct_search
609 self._symbol_c = '%f'
610 self._symbol_f = lambda x: __builtin__.float(x or 0.0)
611 self._symbol_set = (self._symbol_c, self._symbol_f)
613 def search(self, cr, uid, obj, name, args):
614 if not self._fnct_search:
615 #CHECKME: should raise an exception
617 return self._fnct_search(obj, cr, uid, obj, name, args)
619 def get(self, cr, obj, ids, name, user=None, context=None, values=None):
626 res = self._fnct(obj, cr, user, ids, name, self._arg, context)
628 res = self._fnct(cr, obj._table, ids, name, self._arg, context)
630 if self._type == 'binary' and context.get('bin_size', False):
631 # convert the data returned by the function with the size of that data...
632 res = dict(map(lambda (x, y): (x, tools.human_size(len(y))), res.items()))
635 def set(self, cr, obj, id, name, value, user=None, context=None):
639 self._fnct_inv(obj, cr, user, id, name, value, self._fnct_inv_arg, context)
641 # ---------------------------------------------------------
643 # ---------------------------------------------------------
645 class related(function):
647 def _fnct_search(self, tobj, cr, uid, obj=None, name=None, context=None):
650 query = "select %s.id from %s" % (obj._table, obj._table)
651 relation_child = obj._name
653 for i in range(len(self._arg)):
654 field_detail = self._field_get(cr, uid, obj, relation, self._arg[i])
655 relation = field_detail[0]
656 if field_detail[1] in ('one2many', 'many2many'):
657 obj_child = obj.pool.get(field_detail[2][self._arg[i]]['relation'])
658 field_detail_child = obj_child.fields_get(cr, uid,)
660 fields_filter = dict(filter(lambda x: x[1].get('relation', False)
661 and x[1].get('relation') == relation_child
662 and x[1].get('type')=='many2one', field_detail_child.items()))
663 query += " inner join %s on %s.id = %s.%s" % (obj_child._table, obj._table, obj_child._table, fields_filter.keys()[0])
664 relation_child = relation
665 elif field_detail[1] in ('many2one'):
666 obj_child = obj.pool.get(field_detail[2][self._arg[i]]['relation'])
667 obj_child2 = obj.pool.get(relation_child)
668 if obj_child._name == obj_child2._name:
669 # 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');
670 # where +=" %s.id = %s.%s in (select id from %s where %s.%s %s %s"%(obj_child._table,obj_child2._table,self._arg[i])
673 query += " inner join %s on %s.id = %s.%s" % (obj_child._table, obj_child._table, obj_child2._table, self._arg[i])
674 relation_child = field_detail[0]
675 if i == (len(self._arg)-1):
676 if obj_child._inherits:
677 obj_child_inherits = obj.pool.get(obj_child._inherits.keys()[0])
678 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])
679 obj_child = obj_child_inherits
680 where += " %s.%s %s '%%%s%%' and" % (obj_child._table, obj_child._rec_name, context[0][1], context[0][2])
682 obj_child = obj.pool.get(relation_child)
683 if field_detail[1] in ('char'):
684 where += " %s.%s %s '%%%s%%' and" % (obj_child._table, self._arg[i], context[0][1], context[0][2])
685 if field_detail[1] in ('date'):
686 where += " %s.%s %s '%s' and" % (obj_child._table, self._arg[i], context[0][1], context[0][2])
687 if field_detail[1] in ['integer', 'long', 'float','integer_big']:
688 where += " %s.%s %s '%d' and" % (obj_child._table, self._arg[i], context[0][1], context[0][2])
689 query += where.rstrip('and')
692 for id in cr.fetchall():
694 return [('id', 'in', ids)]
696 # def _fnct_write(self,obj,cr, uid, ids,values, field_name, args, context=None):
697 # raise 'Not Implemented Yet'
699 def _fnct_read(self, obj, cr, uid, ids, field_name, args, context=None):
700 if not ids: return {}
703 objlst = obj.browse(cr, uid, ids)
707 for i in range(len(self.arg)):
708 field_detail = self._field_get(cr, uid, obj, relation, self.arg[i])
709 relation = field_detail[0]
710 if not t_data[self.arg[i]]:
713 if field_detail[1] in ('one2many', 'many2many'):
714 t_data = t_data[self.arg[i]][0]
716 t_data = t_data[self.arg[i]]
717 if type(t_data) == type(objlst[0]):
718 res[data.id] = t_data.id
720 res[data.id] = t_data
723 def __init__(self, *arg, **args):
725 super(related, self).__init__(self._fnct_read, arg, fnct_inv_arg=arg, method=True, fnct_search=self._fnct_search, **args)
727 # TODO: call field_get on the object, not in the DB
728 def _field_get(self, cr, uid, obj, model_name, prop):
729 fields = obj.pool.get(model_name).fields_get(cr, uid,)
730 if fields.get(prop, False):
731 return(fields[prop].get('relation', False), fields[prop].get('type', False), fields)
733 raise 'Field %s not exist in %s' % (prop, model_name)
736 # ---------------------------------------------------------
738 # ---------------------------------------------------------
739 class serialized(_column):
740 def __init__(self, string='unknown', serialize_func=repr, deserialize_func=eval, type='text', **args):
741 self._serialize_func = serialize_func
742 self._deserialize_func = deserialize_func
744 self._symbol_set = (self._symbol_c, self._serialize_func)
745 self._symbol_get = self._deserialize_func
746 super(serialized, self).__init__(string=string, **args)
749 class property(function):
751 def _fnct_write(self, obj, cr, uid, id, prop, id_val, val, context=None):
755 definition_id = self._field_get(cr, uid, obj._name, prop)
757 property = obj.pool.get('ir.property')
758 nid = property.search(cr, uid, [('fields_id', '=', definition_id),
759 ('res_id', '=', obj._name+','+str(id))])
761 cr.execute('DELETE FROM ir_property WHERE id=%d', (nid.pop(),))
763 nid = property.search(cr, uid, [('fields_id', '=', definition_id),
764 ('res_id', '=', False)])
767 default_val = property.browse(cr, uid, nid[0], context).value
769 company_id = obj.pool.get('res.users').company_get(cr, uid, uid)
771 newval = (id_val and obj_dest+','+str(id_val)) or False
772 if (newval != default_val) and newval:
773 propdef = obj.pool.get('ir.model.fields').browse(cr, uid,
774 definition_id, context=context)
775 res = property.create(cr, uid, {
776 'name': propdef.name,
778 'res_id': obj._name+','+str(id),
779 'company_id': company_id,
780 'fields_id': definition_id
784 def _fnct_read(self, obj, cr, uid, ids, prop, val, context=None):
787 property = obj.pool.get('ir.property')
788 definition_id = self._field_get(cr, uid, obj._name, prop)
790 nid = property.search(cr, uid, [('fields_id', '=', definition_id),
791 ('res_id', '=', False)])
794 d = property.browse(cr, uid, nid[0], context).value
795 default_val = (d and int(d.split(',')[1])) or False
797 vids = [obj._name + ',' + str(id) for id in ids]
798 nids = property.search(cr, uid, [('fields_id', '=', definition_id),
799 ('res_id', 'in', vids)])
803 res[id] = default_val
804 for prop in property.browse(cr, uid, nids):
805 res[int(prop.res_id.split(',')[1])] = (prop.value and \
806 int(prop.value.split(',')[1])) or False
808 obj = obj.pool.get(self._obj)
809 names = dict(obj.name_get(cr, uid, filter(None, res.values()), context))
811 if res[r] and res[r] in names:
812 res[r] = (res[r], names[res[r]])
817 def _field_get(self, cr, uid, model_name, prop):
818 if not self.field_id.get(cr.dbname):
819 cr.execute('SELECT id \
820 FROM ir_model_fields \
821 WHERE name=%s AND model=%s', (prop, model_name))
823 self.field_id[cr.dbname] = res and res[0]
824 return self.field_id[cr.dbname]
826 def __init__(self, obj_prop, **args):
828 function.__init__(self, self._fnct_read, False, self._fnct_write,
829 (obj_prop, ), **args)
835 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: