removed bad code
[odoo/odoo.git] / bin / osv / fields.py
index daee0e4..800edf5 100644 (file)
@@ -1,30 +1,21 @@
-# -*- encoding: utf-8 -*-
+# -*- coding: utf-8 -*-
 ##############################################################################
+#    
+#    OpenERP, Open Source Management Solution
+#    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
 #
-# Copyright (c) 2004-2008 TINY SPRL. (http://tiny.be) All Rights Reserved.
+#    This program is free software: you can redistribute it and/or modify
+#    it under the terms of the GNU Affero General Public License as
+#    published by the Free Software Foundation, either version 3 of the
+#    License, or (at your option) any later version.
 #
-# $Id$
+#    This program is distributed in the hope that it will be useful,
+#    but WITHOUT ANY WARRANTY; without even the implied warranty of
+#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+#    GNU Affero General Public License for more details.
 #
-# WARNING: This program as such is intended to be used by professional
-# programmers who take the whole responsability of assessing all potential
-# consequences resulting from its eventual inadequacies and bugs
-# End users who are looking for a ready-to-use solution with commercial
-# garantees and support are strongly adviced to contract a Free Software
-# Service Company
-#
-# This program is Free Software; you can redistribute it and/or
-# modify it under the terms of the GNU General Public License
-# as published by the Free Software Foundation; either version 2
-# of the License, or (at your option) any later version.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
+#    You should have received a copy of the GNU Affero General Public License
+#    along with this program.  If not, see <http://www.gnu.org/licenses/>.     
 #
 ##############################################################################
 
@@ -42,8 +33,9 @@
 #
 import string
 import netsvc
+import sys
 
-import psycopg
+from psycopg2 import Binary
 import warnings
 
 import tools
@@ -60,6 +52,7 @@ def _symbol_set(symb):
 class _column(object):
     _classic_read = True
     _classic_write = True
+    _prefetch = True
     _properties = False
     _type = 'unknown'
     _obj = None
@@ -81,23 +74,21 @@ class _column(object):
         self.ondelete = ondelete
         self.translate = translate
         self._domain = domain or []
-        self.relate = False
         self._context = context
         self.write = False
         self.read = False
         self.view_load = 0
         self.select = select
+        self.selectable = True
         for a in args:
             if args[a]:
                 setattr(self, a, args[a])
-        if self.relate:
-            warnings.warn("The relate attribute doesn't work anymore, use act_window tag instead", DeprecationWarning)
 
     def restart(self):
         pass
 
     def set(self, cr, obj, id, name, value, user=None, context=None):
-        cr.execute('update '+obj._table+' set '+name+'='+self._symbol_set[0]+' where id=%d', (self._symbol_set[1](value), id))
+        cr.execute('update '+obj._table+' set '+name+'='+self._symbol_set[0]+' where id=%s', (self._symbol_set[1](value), id))
 
     def set_memory(self, cr, obj, id, name, value, user=None, context=None):
         raise Exception(_('Not implemented set_memory method !'))
@@ -108,9 +99,9 @@ class _column(object):
     def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
         raise Exception(_('undefined get method !'))
 
-    def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None):
-        ids = obj.search(cr, uid, args+self._domain+[(name, 'ilike', value)], offset, limit)
-        res = obj.read(cr, uid, ids, [name])
+    def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, context=None):
+        ids = obj.search(cr, uid, args+self._domain+[(name, 'ilike', value)], offset, limit, context=context)
+        res = obj.read(cr, uid, ids, [name], context=context)
         return [x[name] for x in res]
 
     def search_memory(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, context=None):
@@ -127,9 +118,15 @@ class boolean(_column):
     _symbol_set = (_symbol_c, _symbol_f)
 
 
+class integer_big(_column):
+    _type = 'integer_big'
+    _symbol_c = '%s'
+    _symbol_f = lambda x: int(x or 0)
+    _symbol_set = (_symbol_c, _symbol_f)
+
 class integer(_column):
     _type = 'integer'
-    _symbol_c = '%d'
+    _symbol_c = '%s'
     _symbol_f = lambda x: int(x or 0)
     _symbol_set = (_symbol_c, _symbol_f)
 
@@ -159,13 +156,9 @@ class char(_column):
 
         # we need to convert the string to a unicode object to be able
         # to evaluate its length (and possibly truncate it) reliably
-        if isinstance(symb, str):
-            u_symb = unicode(symb, 'utf8')
-        elif isinstance(symb, unicode):
-            u_symb = symb
-        else:
-            u_symb = unicode(symb)
-        return u_symb.encode('utf8')[:self.size]
+        u_symb = tools.ustr(symb)
+
+        return u_symb[:self.size].encode('utf8')
 
 
 class text(_column):
@@ -173,10 +166,9 @@ class text(_column):
 
 import __builtin__
 
-
 class float(_column):
     _type = 'float'
-    _symbol_c = '%f'
+    _symbol_c = '%s'
     _symbol_f = lambda x: __builtin__.float(x or 0.0)
     _symbol_set = (_symbol_c, _symbol_f)
 
@@ -200,10 +192,12 @@ class time(_column):
 class binary(_column):
     _type = 'binary'
     _symbol_c = '%s'
-    _symbol_f = lambda symb: symb and psycopg.Binary(symb) or None
+    _symbol_f = lambda symb: symb and Binary(symb) or None
     _symbol_set = (_symbol_c, _symbol_f)
+    _symbol_get = lambda self, x: x and str(x)
 
     _classic_read = False
+    _prefetch = False
 
     def __init__(self, string='unknown', filters=None, **args):
         _column.__init__(self, string=string, **args)
@@ -214,7 +208,6 @@ class binary(_column):
             context = {}
         if not values:
             values = []
-
         res = {}
         for i in ids:
             val = None
@@ -222,14 +215,15 @@ class binary(_column):
                 if v['id'] == i:
                     val = v[name]
                     break
-            res.setdefault(i, val)
-            if context.get('bin_size', False):
-                res[i] = tools.human_size(val)
-
+            if context.get('bin_size', False) and val:
+                res[i] = tools.human_size(long(val))
+            else:
+                res[i] = val
         return res
 
     get = get_memory
 
+
 class selection(_column):
     _type = 'selection'
 
@@ -267,29 +261,32 @@ class one2one(_column):
         self._table = obj_src.pool.get(self._obj)._table
         if act[0] == 0:
             id_new = obj.create(cr, user, act[1])
-            cr.execute('update '+obj_src._table+' set '+field+'=%d where id=%d', (id_new, id))
+            cr.execute('update '+obj_src._table+' set '+field+'=%s where id=%s', (id_new, id))
         else:
-            cr.execute('select '+field+' from '+obj_src._table+' where id=%d', (act[0],))
+            cr.execute('select '+field+' from '+obj_src._table+' where id=%s', (act[0],))
             id = cr.fetchone()[0]
             obj.write(cr, user, [id], act[1], context=context)
 
-    def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None):
-        return obj.pool.get(self._obj).search(cr, uid, args+self._domain+[('name', 'like', value)], offset, limit)
+    def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, context=None):
+        return obj.pool.get(self._obj).search(cr, uid, args+self._domain+[('name', 'like', value)], offset, limit, context=context)
 
 
 class many2one(_column):
     _classic_read = False
     _classic_write = True
     _type = 'many2one'
+    _symbol_c = '%s'
+    _symbol_f = lambda x: x or None
+    _symbol_set = (_symbol_c, _symbol_f)
 
     def __init__(self, obj, string='unknown', **args):
         _column.__init__(self, string=string, **args)
         self._obj = obj
 
-    #
-    # TODO: speed improvement
-    #
-    # name is the name of the relation field
+    def set_memory(self, cr, obj, id, field, values, user=None, context=None):
+        obj.datas.setdefault(id, {})
+        obj.datas[id][field] = values
+
     def get_memory(self, cr, obj, ids, name, user=None, context=None, values=None):
         result = {}
         for id in ids:
@@ -307,18 +304,16 @@ class many2one(_column):
         for id in ids:
             res.setdefault(id, '')
         obj = obj.pool.get(self._obj)
+
         # build a dictionary of the form {'id_of_distant_resource': name_of_distant_resource}
         from orm import except_orm
         try:
             names = dict(obj.name_get(cr, user, filter(None, res.values()), context))
         except except_orm:
             names = {}
-
             iids = filter(None, res.values())
-            cr.execute('select id,'+obj._rec_name+' from '+obj._table+' where id in ('+','.join(map(str, iids))+')')
-            for res22 in cr.fetchall():
-                names[res22[0]] = res22[1]
-
+            for iiid in iids:
+                names[iiid] = '// Access Denied //'
         for r in res.keys():
             if res[r] and res[r] in names:
                 res[r] = (res[r], names[res[r]])
@@ -331,32 +326,33 @@ class many2one(_column):
             context = {}
         obj = obj_src.pool.get(self._obj)
         self._table = obj_src.pool.get(self._obj)._table
-        if type(values)==type([]):
+        if type(values) == type([]):
             for act in values:
                 if act[0] == 0:
                     id_new = obj.create(cr, act[2])
-                    cr.execute('update '+obj_src._table+' set '+field+'=%d where id=%d', (id_new, id))
+                    cr.execute('update '+obj_src._table+' set '+field+'=%s where id=%s', (id_new, id))
                 elif act[0] == 1:
                     obj.write(cr, [act[1]], act[2], context=context)
                 elif act[0] == 2:
-                    cr.execute('delete from '+self._table+' where id=%d', (act[1],))
+                    cr.execute('delete from '+self._table+' where id=%s', (act[1],))
                 elif act[0] == 3 or act[0] == 5:
-                    cr.execute('update '+obj_src._table+' set '+field+'=null where id=%d', (id,))
+                    cr.execute('update '+obj_src._table+' set '+field+'=null where id=%s', (id,))
                 elif act[0] == 4:
-                    cr.execute('update '+obj_src._table+' set '+field+'=%d where id=%d', (act[1], id))
+                    cr.execute('update '+obj_src._table+' set '+field+'=%s where id=%s', (act[1], id))
         else:
             if values:
-                cr.execute('update '+obj_src._table+' set '+field+'=%d where id=%d', (values, id))
+                cr.execute('update '+obj_src._table+' set '+field+'=%s where id=%s', (values, id))
             else:
-                cr.execute('update '+obj_src._table+' set '+field+'=null where id=%d', (id,))
+                cr.execute('update '+obj_src._table+' set '+field+'=null where id=%s', (id,))
 
-    def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None):
-        return obj.pool.get(self._obj).search(cr, uid, args+self._domain+[('name', 'like', value)], offset, limit)
+    def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, context=None):
+        return obj.pool.get(self._obj).search(cr, uid, args+self._domain+[('name', 'like', value)], offset, limit, context=context)
 
 
 class one2many(_column):
     _classic_read = False
     _classic_write = False
+    _prefetch = False
     _type = 'one2many'
 
     def __init__(self, obj, fields_id, string='unknown', limit=None, **args):
@@ -370,12 +366,15 @@ class one2many(_column):
     def get_memory(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
         if not context:
             context = {}
+        if self._context:
+            context = context.copy()
+            context.update(self._context)
         if not values:
             values = {}
         res = {}
         for id in ids:
             res[id] = []
-        ids2 = obj.pool.get(self._obj).search(cr, user, [(self._fields_id, 'in', ids)], limit=self._limit)
+        ids2 = obj.pool.get(self._obj).search(cr, user, [(self._fields_id, 'in', ids)], limit=self._limit, context=context)
         for r in obj.pool.get(self._obj).read(cr, user, ids2, [self._fields_id], context=context, load='_classic_write'):
             if r[self._fields_id] in res:
                 res[r[self._fields_id]].append(r['id'])
@@ -384,6 +383,9 @@ class one2many(_column):
     def set_memory(self, cr, obj, id, field, values, user=None, context=None):
         if not context:
             context = {}
+        if self._context:
+            context = context.copy()
+        context.update(self._context)
         if not values:
             return
         obj = obj.pool.get(self._obj)
@@ -413,19 +415,27 @@ class one2many(_column):
     def get(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
         if not context:
             context = {}
+        if self._context:
+            context = context.copy()
+        context.update(self._context)
         if not values:
             values = {}
         res = {}
         for id in ids:
             res[id] = []
-        ids2 = obj.pool.get(self._obj).search(cr, user, [(self._fields_id, 'in', ids)], limit=self._limit)
+        ids2 = obj.pool.get(self._obj).search(cr, user, [(self._fields_id, 'in', ids)], limit=self._limit, context=context)
         for r in obj.pool.get(self._obj)._read_flat(cr, user, ids2, [self._fields_id], context=context, load='_classic_write'):
             res[r[self._fields_id]].append(r['id'])
         return res
 
     def set(self, cr, obj, id, field, values, user=None, context=None):
+        result = []
         if not context:
             context = {}
+        if self._context:
+            context = context.copy()
+        context.update(self._context)
+        context['no_store_function'] = True
         if not values:
             return
         _table = obj.pool.get(self._obj)._table
@@ -433,28 +443,28 @@ class one2many(_column):
         for act in values:
             if act[0] == 0:
                 act[2][self._fields_id] = id
-                obj.create(cr, user, act[2], context=context)
+                id_new = obj.create(cr, user, act[2], context=context)
+                result += obj._store_get_values(cr, user, [id_new], act[2].keys(), context)
             elif act[0] == 1:
                 obj.write(cr, user, [act[1]], act[2], context=context)
             elif act[0] == 2:
                 obj.unlink(cr, user, [act[1]], context=context)
             elif act[0] == 3:
-                cr.execute('update '+_table+' set '+self._fields_id+'=null where id=%d', (act[1],))
+                cr.execute('update '+_table+' set '+self._fields_id+'=null where id=%s', (act[1],))
             elif act[0] == 4:
-                cr.execute('update '+_table+' set '+self._fields_id+'=%d where id=%d', (id, act[1]))
+                cr.execute('update '+_table+' set '+self._fields_id+'=%s where id=%s', (id, act[1]))
             elif act[0] == 5:
-                cr.execute('update '+_table+' set '+self._fields_id+'=null where '+self._fields_id+'=%d', (id,))
+                cr.execute('update '+_table+' set '+self._fields_id+'=null where '+self._fields_id+'=%s', (id,))
             elif act[0] == 6:
-                if not act[2]:
-                    ids2 = [0]
-                else:
-                    ids2 = act[2]
-                cr.execute('update '+_table+' set '+self._fields_id+'=NULL where '+self._fields_id+'=%d and id not in ('+','.join(map(str, ids2))+')', (id,))
-                if act[2]:
-                    cr.execute('update '+_table+' set '+self._fields_id+'=%d where id in ('+','.join(map(str, act[2]))+')', (id,))
+                obj.write(cr, user, act[2], {self._fields_id:id}, context=context or {})
+                ids2 = act[2] or [0]
+                cr.execute('select id from '+_table+' where '+self._fields_id+'=%s and id <> ALL (%s)', (id,ids2))
+                ids3 = map(lambda x:x[0], cr.fetchall())
+                obj.write(cr, user, ids3, {self._fields_id:False}, context=context or {})
+        return result
 
-    def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, operator='like'):
-        return obj.pool.get(self._obj).name_search(cr, uid, value, self._domain, offset, limit)
+    def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, operator='like', context=None):
+        return obj.pool.get(self._obj).name_search(cr, uid, value, self._domain, operator, context=context,limit=limit)
 
 
 #
@@ -469,11 +479,15 @@ class one2many(_column):
 class many2many(_column):
     _classic_read = False
     _classic_write = False
+    _prefetch = False
     _type = 'many2many'
 
     def __init__(self, obj, rel, id1, id2, string='unknown', limit=None, **args):
         _column.__init__(self, string=string, **args)
         self._obj = obj
+        if '.' in rel:
+            raise Exception(_('The second argument of the many2many field %s must be a SQL table !'\
+                'You used %s, which is not a valid SQL table name.')% (string,rel))
         self._rel = rel
         self._id1 = id1
         self._id2 = id2
@@ -489,20 +503,20 @@ class many2many(_column):
             return res
         for id in ids:
             res[id] = []
-        ids_s = ','.join(map(str, ids))
         limit_str = self._limit is not None and ' limit %d' % self._limit or ''
         obj = obj.pool.get(self._obj)
 
-        d1, d2 = obj.pool.get('ir.rule').domain_get(cr, user, obj._name)
+        d1, d2, tables = obj.pool.get('ir.rule').domain_get(cr, user, obj._name, context=context)
         if d1:
-            d1 = ' and '+d1
+            d1 = ' and ' + ' and '.join(d1)
+        else: d1 = ''
 
         cr.execute('SELECT '+self._rel+'.'+self._id2+','+self._rel+'.'+self._id1+' \
-                FROM '+self._rel+' , '+obj._table+' \
-                WHERE '+self._rel+'.'+self._id1+' in ('+ids_s+') \
+                FROM '+self._rel+' , '+(','.join(tables))+' \
+                WHERE '+self._rel+'.'+self._id1+' = ANY (%s) \
                     AND '+self._rel+'.'+self._id2+' = '+obj._table+'.id '+d1
-                +limit_str+' order by '+obj._table+'.'+obj._order+' offset %d',
-                d2+[offset])
+                +limit_str+' order by '+obj._table+'.'+obj._order+' offset %s',
+                [ids,]+d2+[offset])
         for r in cr.fetchall():
             res[r[1]].append(r[0])
         return res
@@ -514,34 +528,38 @@ class many2many(_column):
             return
         obj = obj.pool.get(self._obj)
         for act in values:
+            if not (isinstance(act, list) or isinstance(act, tuple)) or not act:
+                continue
             if act[0] == 0:
                 idnew = obj.create(cr, user, act[2])
-                cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%d,%d)', (id, idnew))
+                cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%s,%s)', (id, idnew))
             elif act[0] == 1:
                 obj.write(cr, user, [act[1]], act[2], context=context)
             elif act[0] == 2:
                 obj.unlink(cr, user, [act[1]], context=context)
             elif act[0] == 3:
-                cr.execute('delete from '+self._rel+' where ' + self._id1 + '=%d and '+ self._id2 + '=%d', (id, act[1]))
+                cr.execute('delete from '+self._rel+' where ' + self._id1 + '=%s and '+ self._id2 + '=%s', (id, act[1]))
             elif act[0] == 4:
-                cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%d,%d)', (id, act[1]))
+                cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%s,%s)', (id, act[1]))
             elif act[0] == 5:
-                cr.execute('update '+self._rel+' set '+self._id2+'=null where '+self._id2+'=%d', (id,))
+                cr.execute('update '+self._rel+' set '+self._id2+'=null where '+self._id2+'=%s', (id,))
             elif act[0] == 6:
 
-                d1, d2 = obj.pool.get('ir.rule').domain_get(cr, user, obj._name)
+                d1, d2,tables = obj.pool.get('ir.rule').domain_get(cr, user, obj._name, context=context)
                 if d1:
-                    d1 = ' and '+d1
-                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)
+                    d1 = ' and ' + ' and '.join(d1)
+                else:
+                    d1 = ''
+                cr.execute('delete from '+self._rel+' where '+self._id1+'=%s AND '+self._id2+' IN (SELECT '+self._rel+'.'+self._id2+' FROM '+self._rel+', '+','.join(tables)+' WHERE '+self._rel+'.'+self._id1+'=%s AND '+self._rel+'.'+self._id2+' = '+obj._table+'.id '+ d1 +')', [id, id]+d2)
 
                 for act_nbr in act[2]:
-                    cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%d, %d)', (id, act_nbr))
+                    cr.execute('insert into '+self._rel+' ('+self._id1+','+self._id2+') values (%s, %s)', (id, act_nbr))
 
     #
     # TODO: use a name_search
     #
-    def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, operator='like'):
-        return obj.pool.get(self._obj).search(cr, uid, args+self._domain+[('name', operator, value)], offset, limit)
+    def search(self, cr, obj, args, name, value, offset=0, limit=None, uid=None, operator='like', context=None):
+        return obj.pool.get(self._obj).search(cr, uid, args+self._domain+[('name', operator, value)], offset, limit, context=context)
 
     def get_memory(self, cr, obj, ids, name, user=None, offset=0, context=None, values=None):
         result = {}
@@ -570,12 +588,23 @@ class many2many(_column):
                 obj.datas[id][name] = act[2]
 
 
+def get_nice_size(a):
+    (x,y) = a
+    if isinstance(y, (int,long)):
+        size = y
+    elif y:
+        size = len(y)
+    else:
+        size = 0
+    return (x, tools.human_size(size))
+
 # ---------------------------------------------------------
 # Function fields
 # ---------------------------------------------------------
 class function(_column):
     _classic_read = False
     _classic_write = False
+    _prefetch = False
     _type = 'function'
     _properties = True
 
@@ -592,22 +621,38 @@ class function(_column):
         self._multi = multi
         if 'relation' in args:
             self._obj = args['relation']
+            
+        if 'digits' in args:
+            self.digits = args['digits']
+        else:
+            self.digits = (16,2)    
+                
         self._fnct_inv_arg = fnct_inv_arg
         if not fnct_inv:
             self.readonly = 1
         self._type = type
         self._fnct_search = fnct_search
         self.store = store
+
+        if not fnct_search and not store:
+            self.selectable = False
+        
+        if store:
+            self._classic_read = True
+            self._classic_write = True
+            if type=='binary':
+                self._symbol_get=lambda x:x and str(x)
+
         if type == 'float':
-            self._symbol_c = '%f'
-            self._symbol_f = lambda x: __builtin__.float(x or 0.0)
-            self._symbol_set = (self._symbol_c, self._symbol_f)
+            self._symbol_c = float._symbol_c
+            self._symbol_f = float._symbol_f
+            self._symbol_set = float._symbol_set
 
-    def search(self, cr, uid, obj, name, args):
+    def search(self, cr, uid, obj, name, args, context=None):
         if not self._fnct_search:
             #CHECKME: should raise an exception
             return []
-        return self._fnct_search(obj, cr, uid, obj, name, args)
+        return self._fnct_search(obj, cr, uid, obj, name, args, context=context)
 
     def get(self, cr, obj, ids, name, user=None, context=None, values=None):
         if not context:
@@ -620,16 +665,33 @@ class function(_column):
         else:
             res = self._fnct(cr, obj._table, ids, name, self._arg, context)
 
+        if self._type == "many2one" :
+            # Filtering only integer/long values if passed
+            res_ids = [x for x in res.values() if x and isinstance(x, (int,long))]
+            
+            if res_ids:
+                obj_model = obj.pool.get(self._obj)
+                dict_names = dict(obj_model.name_get(cr, user, res_ids, context))
+                for r in res.keys():
+                    if res[r] and res[r] in dict_names:
+                        res[r] = (res[r], dict_names[res[r]])
+            
         if self._type == 'binary' and context.get('bin_size', False):
             # convert the data returned by the function with the size of that data...
-            res = dict(map(lambda (x, y): (x, tools.human_size(len(y))), res.items()))
+            res = dict(map( get_nice_size, res.items()))
+        if self._type == "integer":
+            for r in res.keys():
+                # Converting value into string so that it does not affect XML-RPC Limits
+                res[r] = str(res[r])
         return res
+    get_memory = get
 
     def set(self, cr, obj, id, name, value, user=None, context=None):
         if not context:
             context = {}
         if self._fnct_inv:
             self._fnct_inv(obj, cr, user, id, name, value, self._fnct_inv_arg, context)
+    set_memory = set
 
 # ---------------------------------------------------------
 # Related fields
@@ -637,56 +699,136 @@ class function(_column):
 
 class related(function):
 
-    def _fnct_search(self, tobj, cr, uid, obj=None, name=None, context=None):
-        raise 'Not Implemented Yet'
-#        field_detail=self._field_get(cr,uid,obj,obj._name,name)
-#        print field_detail
-#        if field_detail[1] in ('many2one'):
-#            ids=obj.pool.get(field_detail[0] or obj._name).search(cr,uid,[('name','ilike',context[0][2])])
-#            print ids
-#            return [('id','in',[5,6,7])]
-#        return True
-
-
-#    def _fnct_write(self,obj,cr, uid, ids,values, field_name, args, context=None):
-#        raise 'Not Implemented Yet'
-
-    def _fnct_read(self,obj,cr, uid, ids, field_name, args, context=None):
+    def _fnct_search(self, tobj, cr, uid, obj=None, name=None, domain=None, context={}):
+        self._field_get2(cr, uid, obj, context)
+        i = len(self._arg)-1
+        sarg = name
+        while i>0:
+            if type(sarg) in [type([]), type( (1,) )]:
+                where = [(self._arg[i], 'in', sarg)]
+            else:
+                where = [(self._arg[i], '=', sarg)]
+            if domain:
+                where = map(lambda x: (self._arg[i],x[1], x[2]), domain)
+                domain = []
+            sarg = obj.pool.get(self._relations[i]['object']).search(cr, uid, where, context=context)
+            i -= 1
+        return [(self._arg[0], 'in', sarg)]
+
+    def _fnct_write(self,obj,cr, uid, ids, field_name, values, args, context=None):
+        if values and field_name:
+            self._field_get2(cr, uid, obj, context)
+            relation = obj._name
+            res = {}
+            if type(ids) != type([]):
+                ids=[ids]
+            objlst = obj.browse(cr, uid, ids)
+            for data in objlst:
+                t_id=None
+                t_data = data
+                relation = obj._name
+                for i in range(len(self.arg)):
+                    field_detail = self._relations[i]
+                    relation = field_detail['object']
+                    if not t_data[self.arg[i]]:
+                        t_data = False
+                        break
+                    if field_detail['type'] in ('one2many', 'many2many'):
+                        if self._type != "many2one":
+                            t_id=t_data.id
+                            t_data = t_data[self.arg[i]][0]
+                    else:
+                        t_id=t_data['id']
+                        t_data = t_data[self.arg[i]]
+                if t_id:
+                    obj.pool.get(field_detail['object']).write(cr,uid,[t_id],{args[-1]:values}, context=context)
+
+    def _fnct_read(self, obj, cr, uid, ids, field_name, args, context=None):
+        self._field_get2(cr, uid, obj, context)
         if not ids: return {}
-        relation=obj._name
-        res={}
-        objlst = obj.browse(cr,uid,ids)
+        relation = obj._name
+        res = {}.fromkeys(ids, False)
+
+        objlst = obj.browse(cr, uid, ids, context=context)
         for data in objlst:
-            t_data=data
-            relation=obj._name
+            if not data:
+                continue
+            t_data = data
+            relation = obj._name
             for i in range(len(self.arg)):
-                field_detail=self._field_get(cr,uid,obj,relation,self.arg[i])
-                relation=field_detail[0]
-                if not t_data[self.arg[i]]:
+                field_detail = self._relations[i]
+                relation = field_detail['object']
+                try:
+                    if not t_data[self.arg[i]]:
+                        t_data = False
+                        break
+                except:
                     t_data = False
                     break
-                if field_detail[1] in ('one2many','many2many'):
-                    t_data=t_data[self.arg[i]][0]
+                if field_detail['type'] in ('one2many', 'many2many') and i != len(self.arg) - 1:
+                    t_data = t_data[self.arg[i]][0]
                 else:
-                    t_data=t_data[self.arg[i]]
+                    t_data = t_data[self.arg[i]]
             if type(t_data) == type(objlst[0]):
-                res[data.id]=t_data.id
+                res[data.id] = t_data.id
             else:
-                res[data.id]=t_data
+                res[data.id] = t_data
+
+        if self._type=='many2one':
+            ids = filter(None, res.values())
+            if ids:
+                ng = dict(obj.pool.get(self._obj).name_get(cr, uid, ids, context=context))
+                for r in res:
+                    if res[r]:
+                        res[r] = (res[r], ng[res[r]])
+        elif self._type in ('one2many', 'many2many'):
+            for r in res:
+                if res[r]:
+                    res[r] = [x.id for x in res[r]]
+
         return res
 
-    def __init__(self,*arg,**args):
-        print arg
+    def __init__(self, *arg, **args):
         self.arg = arg
-        super(related, self).__init__(self._fnct_read, arg, fnct_inv_arg=arg,method=True, fnct_search=self._fnct_search,**args)
+        self._relations = []
+        super(related, self).__init__(self._fnct_read, arg, self._fnct_write, fnct_inv_arg=arg, method=True, fnct_search=self._fnct_search, **args)
+        if self.store is True:
+            # TODO: improve here to change self.store = {...} according to related objects
+            pass
+
+    def _field_get2(self, cr, uid, obj, context={}):
+        if self._relations:
+            return
+        obj_name = obj._name
+        for i in range(len(self._arg)):
+            f = obj.pool.get(obj_name).fields_get(cr, uid, [self._arg[i]], context=context)[self._arg[i]]
+            self._relations.append({
+                'object': obj_name,
+                'type': f['type']
+
+            })
+            if f.get('relation',False):
+                obj_name = f['relation']
+                self._relations[-1]['relation'] = f['relation']
 
-    # TODO: call field_get on the object, not in the DB
-    def _field_get(self, cr, uid, obj, model_name, prop):
-        fields=obj.pool.get(model_name).fields_get(cr,uid,[prop])
-        if fields.get(prop,False):
-            return(fields[prop].get('relation',False),fields[prop].get('type',False))
-        else:
-            raise 'Fields %s not exist in %s'%(prop,model_name)
+# ---------------------------------------------------------
+# Dummy fields
+# ---------------------------------------------------------
+
+class dummy(function):
+    def _fnct_search(self, tobj, cr, uid, obj=None, name=None, domain=None, context={}):
+        return []
+
+    def _fnct_write(self,obj,cr, uid, ids, field_name, values, args, context=None):
+        return False
+
+    def _fnct_read(self, obj, cr, uid, ids, field_name, args, context=None):
+        return {}
+    
+    def __init__(self, *arg, **args):
+        self.arg = arg
+        self._relations = []
+        super(dummy, self).__init__(self._fnct_read, arg, self._fnct_write, fnct_inv_arg=arg, method=True, fnct_search=None, **args)
 
 # ---------------------------------------------------------
 # Serialized fields
@@ -713,7 +855,7 @@ class property(function):
         nid = property.search(cr, uid, [('fields_id', '=', definition_id),
             ('res_id', '=', obj._name+','+str(id))])
         while len(nid):
-            cr.execute('DELETE FROM ir_property WHERE id=%d', (nid.pop(),))
+            cr.execute('DELETE FROM ir_property WHERE id=%s', (nid.pop(),))
 
         nid = property.search(cr, uid, [('fields_id', '=', definition_id),
             ('res_id', '=', False)])
@@ -721,9 +863,12 @@ class property(function):
         if nid:
             default_val = property.browse(cr, uid, nid[0], context).value
 
-        company_id = obj.pool.get('res.users').company_get(cr, uid, uid)
+        company_id = obj.pool.get('res.company')._company_default_get(cr, uid, obj._name, prop, context=context)
         res = False
-        newval = (id_val and obj_dest+','+str(id_val)) or False
+        if val[0]:
+            newval = (id_val and obj_dest+','+str(id_val)) or False
+        else:
+            newval = id_val or False
         if (newval != default_val) and newval:
             propdef = obj.pool.get('ir.model.fields').browse(cr, uid,
                     definition_id, context=context)
@@ -757,16 +902,28 @@ class property(function):
         for id in ids:
             res[id] = default_val
         for prop in property.browse(cr, uid, nids):
-            res[int(prop.res_id.split(',')[1])] = (prop.value and \
-                    int(prop.value.split(',')[1])) or False
-
-        obj = obj.pool.get(self._obj)
-        names = dict(obj.name_get(cr, uid, filter(None, res.values()), context))
-        for r in res.keys():
-            if res[r] and res[r] in names:
-                res[r] = (res[r], names[res[r]])
+            if prop.value.find(',') >= 0:
+                res[int(prop.res_id.split(',')[1])] = (prop.value and \
+                        int(prop.value.split(',')[1])) or False
             else:
-                res[r] = False
+                res[int(prop.res_id.split(',')[1])] = prop.value or ''
+
+        if self._obj:
+            obj = obj.pool.get(self._obj)
+            to_check = res.values()
+            if default_val and default_val not in to_check:
+                to_check += [default_val]
+            existing_ids = obj.search(cr, uid, [('id', 'in', to_check)])
+            for id, res_id in res.items():
+                if res_id not in existing_ids:
+                    cr.execute('DELETE FROM ir_property WHERE value=%s', ((obj._name+','+str(res_id)),))
+                    res[id] = default_val
+            names = dict(obj.name_get(cr, uid, existing_ids, context))
+            for r in res.keys():
+                if res[r] and res[r] in names:
+                    res[r] = (res[r], names[res[r]])
+                else:
+                    res[r] = False
         return res
 
     def _field_get(self, cr, uid, model_name, prop):