Domain evaluation : Conditions like [(field,'in',[])],[(field,'not in',[])] considered
[odoo/odoo.git] / bin / osv / expression.py
index feac469..8c4bd58 100644 (file)
@@ -44,18 +44,28 @@ class expression(object):
            and (((not internal) and element[1] in OPS) \
                 or (internal and element[1] in INTERNAL_OPS))
 
-    def __execute_recursive_in(self, cr, s, f, w, ids):
+    def __execute_recursive_in(self, cr, s, f, w, ids, op, type):
         res = []
-        for i in range(0, len(ids), cr.IN_MAX):
-            subids = ids[i:i+cr.IN_MAX]
-            cr.execute('SELECT "%s"'    \
-                       '  FROM "%s"'    \
-                       ' WHERE "%s" in (%s)' % (s, f, w, ','.join(['%s']*len(subids))),
-                       subids)
+        if ids:
+            if op in ['<','>','>=','<=']:
+                cr.execute('SELECT "%s"'    \
+                               '  FROM "%s"'    \
+                               ' WHERE "%s" %s %s' % (s, f, w, op, ids[0]))
+                res.extend([r[0] for r in cr.fetchall()])
+            else:
+                for i in range(0, len(ids), cr.IN_MAX):
+                    subids = ids[i:i+cr.IN_MAX]
+                    cr.execute('SELECT "%s"'    \
+                               '  FROM "%s"'    \
+                               ' WHERE "%s" in (%s)' % (s, f, w, ','.join(['%s']*len(subids))),
+                               subids)
+                    res.extend([r[0] for r in cr.fetchall()])
+        else:
+            cr.execute('SELECT distinct("%s")'    \
+                           '  FROM "%s" where "%s" is not null'  % (s, f, s)),
             res.extend([r[0] for r in cr.fetchall()])
         return res
 
-
     def __init__(self, exp):
         # check if the expression is valid
         if not reduce(lambda acc, val: acc and (self._is_operator(val) or self._is_leaf(val)), exp, True):
@@ -101,16 +111,24 @@ class expression(object):
             if self._is_operator(e) or e == self.__DUMMY_LEAF:
                 continue
             left, operator, right = e
-
             working_table = table
-            if left in table._inherit_fields:
-                working_table = table.pool.get(table._inherit_fields[left][0])
-                if working_table not in self.__tables.values():
-                    self.__joins.append(('%s.%s=%s.%s' % (working_table._table, 'id', table._table, table._inherits[working_table._name]), working_table._table))
-
-            self.__tables[i] = working_table
-
+            main_table = table
             fargs = left.split('.', 1)
+            index = i
+            if left in table._inherit_fields:
+                while True:
+                    field = main_table._columns.get(fargs[0], False)
+                    if field:
+                        working_table = main_table
+                        self.__tables[i] = working_table
+                        break
+                    working_table = main_table.pool.get(main_table._inherit_fields[left][0])
+                    if working_table not in self.__tables.values():
+                        self.__joins.append(('%s.%s=%s.%s' % (working_table._table, 'id', main_table._table, main_table._inherits[working_table._name]), working_table._table))
+                        self.__tables[index] = working_table
+                        index += 1
+                    main_table = working_table
+            
             field = working_table._columns.get(fargs[0], False)
             if not field:
                 if left == 'id' and operator == 'child_of':
@@ -123,6 +141,12 @@ class expression(object):
                 if field._type == 'many2one':
                     right = field_obj.search(cr, uid, [(fargs[1], operator, right)], context=context)
                     self.__exp[i] = (fargs[0], 'in', right)
+                # Making search easier when there is a left operand as field.o2m or field.m2m
+                if field._type in ['many2many','one2many']:
+                    right = field_obj.search(cr, uid, [(fargs[1], operator, right)], context=context)
+                    right1 = table.search(cr, uid, [(fargs[0],'in', right)], context=context)
+                    self.__exp[i] = ('id', 'in', right1)                    
+                
                 continue
 
             if field._properties:
@@ -133,7 +157,7 @@ class expression(object):
                         # values in the database, so we must ignore it : we generate a dummy leaf
                         self.__exp[i] = self.__DUMMY_LEAF
                     else:
-                        subexp = field.search(cr, uid, table, left, [self.__exp[i]])
+                        subexp = field.search(cr, uid, table, left, [self.__exp[i]], context=context)
                         # we assume that the expression is valid
                         # we create a dummy leaf for forcing the parsing of the resulting expression
                         self.__exp[i] = '&'
@@ -145,37 +169,89 @@ class expression(object):
 
 
             elif field._type == 'one2many':
-                if isinstance(right, basestring):
-                    ids2 = [x[0] for x in field_obj.name_search(cr, uid, right, [], operator, limit=None)]
-                else:
-                    ids2 = list(right)
-                if not ids2:
-                    self.__exp[i] = ('id', '=', '0')
-                else:
-                    self.__exp[i] = ('id', 'in', self.__execute_recursive_in(cr, field._fields_id, field_obj._table, 'id', ids2))
+                # Applying recursivity on field(one2many)
+                if operator == 'child_of':
+                    if isinstance(right, basestring):
+                        ids2 = [x[0] for x in field_obj.name_search(cr, uid, right, [], 'like', context=context, limit=None)]
+                    else:
+                        ids2 = list(right)
+                    if field._obj != working_table._name:
+                        dom = _rec_get(ids2, field_obj, left=left, prefix=field._obj)
+                    else:
+                        dom = _rec_get(ids2, working_table, parent=left)
+                    self.__exp = self.__exp[:i] + dom + self.__exp[i+1:]
+                
+                else:    
+                    call_null = True
+                    
+                    if right:
+                        if isinstance(right, basestring):
+                            ids2 = [x[0] for x in field_obj.name_search(cr, uid, right, [], operator, context=context, limit=None)]
+                            operator = 'in' 
+                        else:
+                            if not isinstance(right,list):
+                                ids2 = [right]
+                            else:
+                                ids2 = right    
+                        if not ids2:
+                            call_null = True
+                            operator = 'in' # operator changed because ids are directly related to main object
+                        else:
+                            call_null = False
+                            o2m_op = 'in'
+                            if operator in  ['not like','not ilike','not in','<>','!=']:
+                                o2m_op = 'not in'
+                            self.__exp[i] = ('id', o2m_op, self.__execute_recursive_in(cr, field._fields_id, field_obj._table, 'id', ids2, operator, field._type))
+                    
+                    if call_null:
+                        o2m_op = 'not in'
+                        if operator in  ['not like','not ilike','not in','<>','!=']:
+                            o2m_op = 'in'                         
+                        self.__exp[i] = ('id', o2m_op, self.__execute_recursive_in(cr, field._fields_id, field_obj._table, 'id', [], operator, field._type) or [0])      
 
             elif field._type == 'many2many':
                 #FIXME
                 if operator == 'child_of':
                     if isinstance(right, basestring):
-                        ids2 = [x[0] for x in field_obj.name_search(cr, uid, right, [], 'like', limit=None)]
+                        ids2 = [x[0] for x in field_obj.name_search(cr, uid, right, [], 'like', context=context, limit=None)]
                     else:
                         ids2 = list(right)
 
                     def _rec_convert(ids):
                         if field_obj == table:
                             return ids
-                        return self.__execute_recursive_in(cr, field._id1, field._rel, field._id2, ids)
+                        return self.__execute_recursive_in(cr, field._id1, field._rel, field._id2, ids, operator, field._type)
 
                     dom = _rec_get(ids2, field_obj)
                     ids2 = field_obj.search(cr, uid, dom, context=context)
                     self.__exp[i] = ('id', 'in', _rec_convert(ids2))
                 else:
-                    if isinstance(right, basestring):
-                        res_ids = [x[0] for x in field_obj.name_search(cr, uid, right, [], operator)]
-                    else:
-                        res_ids = list(right)
-                    self.__exp[i] = ('id', 'in', self.__execute_recursive_in(cr, field._id1, field._rel, field._id2, res_ids) or [0])
+                    call_null_m2m = True
+                    if right:
+                        if isinstance(right, basestring):
+                            res_ids = [x[0] for x in field_obj.name_search(cr, uid, right, [], operator, context=context)]
+                            operator = 'in'
+                        else:
+                            if not isinstance(right, list):
+                                res_ids = [right]
+                            else:
+                                res_ids = right
+                        if not res_ids:
+                            call_null_m2m = True
+                            operator = 'in' # operator changed because ids are directly related to main object
+                        else:
+                            call_null_m2m = False
+                            m2m_op = 'in'        
+                            if operator in  ['not like','not ilike','not in','<>','!=']:
+                                m2m_op = 'not in'
+                            
+                            self.__exp[i] = ('id', m2m_op, self.__execute_recursive_in(cr, field._id1, field._rel, field._id2, res_ids, operator, field._type) or [0])
+                    if call_null_m2m:
+                        m2m_op = 'not in'
+                        if operator in  ['not like','not ilike','not in','<>','!=']:
+                            m2m_op = 'in'                         
+                        self.__exp[i] = ('id', m2m_op, self.__execute_recursive_in(cr, field._id1, field._rel, field._id2, [], operator,  field._type) or [0])
+                        
             elif field._type == 'many2one':
                 if operator == 'child_of':
                     if isinstance(right, basestring):
@@ -200,11 +276,16 @@ class expression(object):
                 # other field type
                 # add the time part to datetime field when it's not there:
                 if field._type == 'datetime' and self.__exp[i][2] and len(self.__exp[i][2]) == 10:
+                    
+                    self.__exp[i] = list(self.__exp[i])
+                    
                     if operator in ('>', '>='):
                         self.__exp[i][2] += ' 00:00:00'
                     elif operator in ('<', '<='):
                         self.__exp[i][2] += ' 23:59:59'
-
+                    
+                    self.__exp[i] = tuple(self.__exp[i])
+                        
                 if field.translate:
                     if operator in ('like', 'ilike', 'not like', 'not ilike'):
                         right = '%%%s%%' % right
@@ -252,7 +333,7 @@ class expression(object):
             query = '(%s.%s in (%s))' % (table._table, left, right[0])
             params = right[1]
         elif operator in ['in', 'not in']:
-            params = right[:]
+            params = right and right[:] or []
             len_before = len(params)
             for i in range(len_before)[::-1]:
                 if params[i] == False:
@@ -261,14 +342,19 @@ class expression(object):
             len_after = len(params)
             check_nulls = len_after != len_before
             query = '(1=0)'
-
+            
             if len_after:
                 if left == 'id':
                     instr = ','.join(['%s'] * len_after)
                 else:
                     instr = ','.join([table._columns[left]._symbol_set[0]] * len_after)
                 query = '(%s.%s %s (%s))' % (table._table, left, operator, instr)
-
+            else:
+                # the case for [field, 'in', []] or [left, 'not in', []]
+                if operator == 'in':
+                    query = '(%s.%s IS NULL)' % (table._table, left)
+                else:
+                    query = '(%s.%s IS NOT NULL)' % (table._table, left)
             if check_nulls:
                 query = '(%s OR %s.%s IS NULL)' % (query, table._table, left)
         else: