1 # -*- encoding: iso-8859-1 -*-
2 ##############################################################################
4 # Copyright (c) 2004-2006 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
51 def _symbol_set(symb):
52 if symb==None or symb==False:
54 elif isinstance(symb, unicode):
55 return symb.encode('utf-8')
58 class _column(object):
65 _symbol_f = _symbol_set
66 _symbol_set = (_symbol_c, _symbol_f)
69 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):
70 self.states = states or {}
72 self.readonly = readonly
73 self.required = required
75 self.help = args.get('help', '')
76 self.priority = priority
77 self.change_default = change_default
78 self.ondelete = ondelete
79 self.translate = translate
80 self._domain = domain or []
82 self._context = context
83 self.group_name = False
88 setattr(self, a, args[a])
90 warnings.warn("The relate attribute doesn't work anymore, use act_window tag instead", DeprecationWarning)
95 def set(self, cr, obj, id, name, value, user=None, context=None):
96 cr.execute('update '+obj._table+' set '+name+'='+self._symbol_set[0]+' where id=%d', (self._symbol_set[1](value),id) )
98 def get(self, cr, obj, ids, name, context=None, values=None):
99 raise Exception, 'undefined get method !'
101 def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None):
102 ids = obj.search(cr, uid, args+self._domain+[(name,'ilike',value)], offset, limit)
103 res = obj.read(cr, uid, ids, [name])
104 return [x[name] for x in res]
106 # ---------------------------------------------------------
108 # ---------------------------------------------------------
109 class boolean(_column):
112 _symbol_f = lambda x: x and 'True' or 'False'
113 _symbol_set = (_symbol_c, _symbol_f)
115 class integer(_column):
118 _symbol_f = lambda x: int(x or 0)
119 _symbol_set = (_symbol_c, _symbol_f)
121 class reference(_column):
123 def __init__(self, string, selection, size, **args):
124 _column.__init__(self, string=string, size=size, selection=selection, **args)
129 def __init__(self, string, size, **args):
130 _column.__init__(self, string=string, size=size, **args)
131 self._symbol_set = (self._symbol_c, self._symbol_set_char)
133 # takes a string (encoded in utf8) and returns a string (encoded in utf8)
134 def _symbol_set_char(self, symb):
136 # * we need to remove the "symb==False" from the next line BUT
137 # for now too many things rely on this broken behavior
138 # * the symb==None test should be common to all data types
139 if symb==None or symb==False:
142 # we need to convert the string to a unicode object to be able
143 # to evaluate its length (and possibly truncate it) reliably
144 if isinstance(symb, str):
145 u_symb = unicode(symb, 'utf8')
146 elif isinstance(symb, unicode):
149 u_symb = unicode(symb)
151 if len(u_symb) > self.size:
152 return u_symb[:self.size-3].encode('utf8') + '...'
154 return u_symb.encode('utf8')
161 class float(_column):
164 _symbol_f = lambda x: __builtin__.float(x or 0.0)
165 _symbol_set = (_symbol_c, _symbol_f)
166 def __init__(self, string='unknown', digits=None, **args):
167 _column.__init__(self, string=string, **args)
170 # We'll need to use decimal one day or another
174 # from tools import decimal
176 #class float(_column):
179 # def __init__(self, string='unknown', digits=None, **args):
180 # _column.__init__(self, string=string, **args)
181 # self._symbol_set = (self._symbol_c, self._symbol_set_decimal)
182 # self.digits = digits
187 # self._scale = decimal.Decimal(str(10**-scale))
188 # self._context = decimal.Context(prec=scale, rounding=decimal.ROUND_HALF_UP)
190 # def _symbol_set_decimal(self, symb):
191 # if isinstance(symb, __builtin__.float):
192 # return decimal.Decimal('%f' % symb)
193 # return decimal.Decimal(symb)
198 class datetime(_column):
204 class binary(_column):
207 _symbol_f = lambda symb: symb and psycopg.Binary(symb) or None
208 _symbol_set = (_symbol_c, _symbol_f)
210 class selection(_column):
213 def __init__(self, selection, string='unknown', **args):
214 _column.__init__(self, string=string, **args)
215 self.selection = selection
217 def set(self, cr, obj, id, name, value, user=None, context=None):
220 #CHECKME: a priori, ceci n'est jamais appelé puisque le test ci-dessous est mauvais
221 # la raison est que selection n'est pas en classic_write = false
222 # a noter qu'on pourrait fournir un _symbol_set specifique, et ca suffirait
223 if value in self.selection:
224 raise Exception, 'BAD VALUE'
225 _column.set(self, cr, obj, id, name, value, user=None, context=context)
228 # ---------------------------------------------------------
230 # ---------------------------------------------------------
233 # Values: (0, 0, { fields }) create
234 # (1, ID, { fields }) modification
235 # (2, ID) remove (delete)
236 # (3, ID) unlink one (target id or target of relation)
238 # (5) unlink all (only valid for one2many)
240 #CHECKME: dans la pratique c'est quoi la syntaxe utilisee pour le 5? (5) ou (5, 0)?
241 class one2one(_column):
242 _classic_read = False
243 _classic_write = True
246 def __init__(self, obj, string='unknown', **args):
247 warnings.warn("The one2one field doesn't work anymore", DeprecationWarning)
248 _column.__init__(self, string=string, **args)
251 def set(self, cr, obj_src, id, field, act, user=None, context=None):
254 obj = obj_src.pool.get(self._obj)
255 self._table = obj_src.pool.get(self._obj)._table
257 id_new = obj.create(cr, user, act[1])
258 cr.execute('update '+obj_src._table+' set '+field+'=%d where id=%d', (id_new,id))
260 cr.execute('select '+field+' from '+obj_src._table+' where id=%d', (act[0],))
262 obj.write(cr, user, [id] , act[1], context=context)
264 def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None):
265 return obj.pool.get(self._obj).search(cr, uid, args+self._domain+[('name','like',value)], offset, limit)
268 class many2one(_column):
269 _classic_read = False
270 _classic_write = True
273 def __init__(self, obj, string='unknown', **args):
274 _column.__init__(self, string=string, **args)
278 # TODO: speed improvement
280 # name is the name of the relation field
281 def get(self, cr, obj, ids, name, user=None, context=None, values=None):
288 res[r['id']] = r[name]
290 res.setdefault(id, '')
291 obj = obj.pool.get(self._obj)
292 # build a dictionary of the form {'id_of_distant_resource': name_of_distant_resource}
293 from orm import except_orm
295 names = dict(obj.name_get(cr, user, filter(None, res.values()), context))
299 iids = filter(None, res.values())
300 cr.execute('select id,'+obj._rec_name+' from '+obj._table+' where id in ('+','.join(map(str,iids))+')')
301 for res22 in cr.fetchall():
302 names[res22[0]] = res22[1]
305 if res[r] and res[r] in names:
306 res[r] = (res[r], names[res[r]])
311 def set(self, cr, obj_src, id, field, values, user=None, context=None):
314 obj = obj_src.pool.get(self._obj)
315 self._table = obj_src.pool.get(self._obj)._table
316 if type(values)==type([]):
319 id_new = obj.create(cr, act[2])
320 cr.execute('update '+obj_src._table+' set '+field+'=%d where id=%d', (id_new,id))
322 obj.write(cr, [act[1]], act[2], context=context)
324 cr.execute('delete from '+self._table+' where id=%d', (act[1],))
325 elif act[0]==3 or act[0]==5:
326 cr.execute('update '+obj_src._table+' set '+field+'=null where id=%d', (id,))
328 cr.execute('update '+obj_src._table+' set '+field+'=%d where id=%d', (act[1],id))
331 cr.execute('update '+obj_src._table+' set '+field+'=%d where id=%d', (values,id))
333 cr.execute('update '+obj_src._table+' set '+field+'=null where id=%d', (id,))
335 def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None):
336 return obj.pool.get(self._obj).search(cr, uid, args+self._domain+[('name','like',value)], offset, limit)
338 class one2many(_column):
339 _classic_read = False
340 _classic_write = False
343 def __init__(self, obj, fields_id, string='unknown', limit=None, **args):
344 _column.__init__(self, string=string, **args)
346 self._fields_id = fields_id
348 #one2many can't be used as condition for defaults
349 assert(self.change_default != True)
351 def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
359 ids2 = obj.pool.get(self._obj).search(cr, user, [(self._fields_id,'in',ids)], limit=self._limit)
360 for r in obj.pool.get(self._obj)._read_flat(cr, user, ids2, [self._fields_id], context=context, load='_classic_write'):
361 res[r[self._fields_id]].append( r['id'] )
364 def set(self, cr, obj, id, field, values, user=None, context=None):
369 _table = obj.pool.get(self._obj)._table
370 obj = obj.pool.get(self._obj)
373 act[2][self._fields_id] = id
374 obj.create(cr, user, act[2], context=context)
376 obj.write(cr, user, [act[1]] , act[2], context=context)
378 obj.unlink(cr, user, [act[1]], context=context)
380 cr.execute('update '+_table+' set '+self._fields_id+'=null where id=%d', (act[1],))
382 cr.execute('update '+_table+' set '+self._fields_id+'=%d where id=%d', (id,act[1]))
384 cr.execute('update '+_table+' set '+self._fields_id+'=null where '+self._fields_id+'=%d', (id,))
390 cr.execute('update '+_table+' set '+self._fields_id+'=NULL where '+self._fields_id+'=%d and id not in ('+','.join(map(str, ids2))+')', (id,))
392 cr.execute('update '+_table+' set '+self._fields_id+'=%d where id in ('+','.join(map(str, act[2]))+')', (id,))
393 def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, operator='like'):
394 return obj.pool.get(self._obj).name_search(cr, uid, value, self._domain, offset, limit)
397 # Values: (0, 0, { fields }) create
398 # (1, ID, { fields }) modification
403 # (6, ?, ids) set a list of links
405 class many2many(_column):
406 _classic_read = False
407 _classic_write = False
410 def __init__(self, obj, rel, id1, id2, string='unknown', limit=None, **args):
411 _column.__init__(self, string=string, **args)
418 def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
428 ids_s = ','.join(map(str,ids))
429 limit_str = self._limit is not None and ' limit %d' % self._limit or ''
430 obj = obj.pool.get(self._obj)
432 d1, d2 = obj.pool.get('ir.rule').domain_get(cr, user, obj._name)
436 cr.execute('SELECT '+self._rel+'.'+self._id2+','+self._rel+'.'+self._id1+' \
437 FROM '+self._rel+' , '+obj._table+' \
438 WHERE '+self._rel+'.'+self._id1+' in ('+ids_s+') \
439 AND '+self._rel+'.'+self._id2+' = '+obj._table+'.id '+d1
440 +limit_str+' order by '+obj._table+'.'+obj._order+' offset %d',
442 for r in cr.fetchall():
443 res[r[1]].append(r[0])
446 def set(self, cr, obj, id, name, values, user=None, context=None):
451 obj = obj.pool.get(self._obj)
454 idnew = obj.create(cr, user, act[2])
455 cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%d,%d)', (id,idnew))
457 obj.write(cr, user, [act[1]] , act[2], context=context)
459 obj.unlink(cr, user, [act[1]], context=context)
461 cr.execute('delete from '+self._rel+' where ' + self._id1 + '=%d and '+ self._id2 + '=%d', (id,act[1]))
463 cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%d,%d)', (id,act[1]))
465 cr.execute('update '+self._rel+' set '+self._id2+'=null where '+self._id2+'=%d', (id,))
468 d1, d2 = obj.pool.get('ir.rule').domain_get(cr, user, obj._name)
471 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 )
473 for act_nbr in act[2]:
474 cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%d, %d)', (id, act_nbr))
477 # TODO: use a name_search
479 def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, operator='like'):
480 return obj.pool.get(self._obj).search(cr, uid, args+self._domain+[('name',operator,value)], offset, limit)
482 # ---------------------------------------------------------
484 # ---------------------------------------------------------
486 class function(_column):
487 _classic_read = False
488 _classic_write = False
492 def __init__(self, fnct, arg=None, fnct_inv=None, fnct_inv_arg=None, type='float', fnct_search=None, obj=None, method=False, store=False, **args):
493 _column.__init__(self, **args)
495 self._method = method
497 self._fnct_inv = fnct_inv
499 if 'relation' in args:
500 self._obj = args['relation']
501 self._fnct_inv_arg = fnct_inv_arg
505 self._fnct_search = fnct_search
508 self._symbol_c = '%f'
509 self._symbol_f = lambda x: __builtin__.float(x or 0.0)
510 self._symbol_set = (self._symbol_c, self._symbol_f)
512 def search(self, cr, uid, obj, name, args):
513 if not self._fnct_search:
514 #CHECKME: should raise an exception
516 return self._fnct_search(obj, cr, uid, obj, name, args)
518 def get(self, cr, obj, ids, name, user=None, context=None, values=None):
526 # TODO get HAS to receive uid for permissions !
527 return self._fnct(obj, cr, user, ids, name, self._arg, context)
529 return self._fnct(cr, table, ids, name, self._arg, context)
531 def set(self, cr, obj, id, name, value, user=None, context=None):
535 self._fnct_inv(obj, cr, user, id, name, value, self._fnct_inv_arg, context)
537 # ---------------------------------------------------------
539 # ---------------------------------------------------------
540 class serialized(_column):
541 def __init__(self, string='unknown', serialize_func=repr, deserialize_func=eval, type='text', **args):
542 self._serialize_func = serialize_func
543 self._deserialize_func = deserialize_func
545 self._symbol_set = (self._symbol_c, self._serialize_func)
546 self._symbol_get = self._deserialize_func
547 super(serialized, self).__init__(string=string, **args)
550 class property(function):
552 def _fnct_write(self, obj, cr, uid, id, prop, id_val, val, context=None):
556 definition_id = self._field_get(cr, uid, obj._name, prop)
558 property = obj.pool.get('ir.property')
559 nid = property.search(cr, uid, [('fields_id', '=', definition_id),
560 ('res_id', '=', obj._name+','+str(id))])
562 cr.execute('DELETE FROM ir_property WHERE id=%d', (nid.pop(),))
564 nid = property.search(cr, uid, [('fields_id', '=', definition_id),
565 ('res_id', '=', False)])
568 default_val = property.browse(cr, uid, nid[0], context).value
570 company_id = obj.pool.get('res.users').company_get(cr, uid, uid)
572 newval = (id_val and obj_dest+','+str(id_val)) or False
573 if (newval != default_val) and newval:
574 propdef = obj.pool.get('ir.model.fields').browse(cr, uid,
575 definition_id, context=context)
576 res = property.create(cr, uid, {
577 'name': propdef.name,
579 'res_id': obj._name+','+str(id),
580 'company_id': company_id,
581 'fields_id': definition_id
585 def _fnct_read(self, obj, cr, uid, ids, prop, val, context=None):
588 property = obj.pool.get('ir.property')
589 definition_id = self._field_get(cr, uid, obj._name, prop)
591 nid = property.search(cr, uid, [('fields_id', '=', definition_id),
592 ('res_id', '=', False)])
595 d = property.browse(cr, uid, nid[0], context).value
596 default_val = (d and int(d.split(',')[1])) or False
598 vids = [obj._name + ',' + str(id) for id in ids]
599 nids = property.search(cr, uid, [('fields_id', '=', definition_id),
600 ('res_id', 'in', vids)])
605 for prop in property.browse(cr, uid, nids):
606 res[int(prop.res_id.split(',')[1])] = (prop.value and \
607 int(prop.value.split(',')[1])) or False
609 obj = obj.pool.get(self._obj)
610 names = dict(obj.name_get(cr, uid, filter(None, res.values()), context))
612 if res[r] and res[r] in names:
613 res[r] = (res[r], names[res[r]])
618 def _field_get(self, cr, uid, model_name, prop):
619 if not self.field_id.get(cr.dbname):
620 cr.execute('SELECT id \
621 FROM ir_model_fields \
622 WHERE name=%s AND model=%s', (prop, model_name))
624 self.field_id[cr.dbname] = res and res[0]
625 return self.field_id[cr.dbname]
627 def __init__(self, obj_prop, **args):
629 function.__init__(self, self._fnct_read, False, self._fnct_write,
630 (obj_prop, ), **args)