Domain evaluation : Conditions like [(field,'in',[])],[(field,'not in',[])] considered
[odoo/odoo.git] / bin / osv / expression.py
1 #!/usr/bin/env python
2 # -*- encoding: utf-8 -*-
3 ##############################################################################
4 #
5 #    OpenERP, Open Source Management Solution   
6 #    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>). All Rights Reserved
7 #    $Id$
8 #
9 #    This program is free software: you can redistribute it and/or modify
10 #    it under the terms of the GNU General Public License as published by
11 #    the Free Software Foundation, either version 3 of the License, or
12 #    (at your option) any later version.
13 #
14 #    This program is distributed in the hope that it will be useful,
15 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
16 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 #    GNU General Public License for more details.
18 #
19 #    You should have received a copy of the GNU General Public License
20 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
21 #
22 ##############################################################################
23
24 from tools import flatten, reverse_enumerate
25 import fields
26
27
28 class expression(object):
29     """
30     parse a domain expression
31     use a real polish notation
32     leafs are still in a ('foo', '=', 'bar') format
33     For more info: http://christophe-simonis-at-tiny.blogspot.com/2008/08/new-new-domain-notation.html 
34     """
35
36     def _is_operator(self, element):
37         return isinstance(element, (str, unicode)) and element in ['&', '|', '!']
38
39     def _is_leaf(self, element, internal=False):
40         OPS = ('=', '!=', '<>', '<=', '<', '>', '>=', '=like', 'like', 'not like', 'ilike', 'not ilike', 'in', 'not in', 'child_of')
41         INTERNAL_OPS = OPS + ('inselect',)
42         return (isinstance(element, tuple) or isinstance(element, list)) \
43            and len(element) == 3 \
44            and (((not internal) and element[1] in OPS) \
45                 or (internal and element[1] in INTERNAL_OPS))
46
47     def __execute_recursive_in(self, cr, s, f, w, ids, op, type):
48         res = []
49         if ids:
50             if op in ['<','>','>=','<=']:
51                 cr.execute('SELECT "%s"'    \
52                                '  FROM "%s"'    \
53                                ' WHERE "%s" %s %s' % (s, f, w, op, ids[0]))
54                 res.extend([r[0] for r in cr.fetchall()])
55             else:
56                 for i in range(0, len(ids), cr.IN_MAX):
57                     subids = ids[i:i+cr.IN_MAX]
58                     cr.execute('SELECT "%s"'    \
59                                '  FROM "%s"'    \
60                                ' WHERE "%s" in (%s)' % (s, f, w, ','.join(['%s']*len(subids))),
61                                subids)
62                     res.extend([r[0] for r in cr.fetchall()])
63         else:
64             cr.execute('SELECT distinct("%s")'    \
65                            '  FROM "%s" where "%s" is not null'  % (s, f, s)),
66             res.extend([r[0] for r in cr.fetchall()])
67         return res
68
69     def __init__(self, exp):
70         # check if the expression is valid
71         if not reduce(lambda acc, val: acc and (self._is_operator(val) or self._is_leaf(val)), exp, True):
72             raise ValueError('Bad domain expression: %r' % (exp,))
73         self.__exp = exp
74         self.__tables = {}  # used to store the table to use for the sql generation. key = index of the leaf
75         self.__joins = []
76         self.__main_table = None # 'root' table. set by parse()
77         self.__DUMMY_LEAF = (1, '=', 1) # a dummy leaf that must not be parsed or sql generated
78
79
80     def parse(self, cr, uid, table, context):
81         """ transform the leafs of the expression """
82         if not self.__exp:
83             return self
84
85         def _rec_get(ids, table, parent=None, left='id', prefix=''):
86             if table._parent_store and (not table.pool._init):
87 # TODO: Improve where joins are implemented for many with '.', replace by:
88 # doms += ['&',(prefix+'.parent_left','<',o.parent_right),(prefix+'.parent_left','>=',o.parent_left)]
89                 doms = []
90                 for o in table.browse(cr, uid, ids, context=context):
91                     if doms:
92                         doms.insert(0, '|')
93                     doms += ['&', ('parent_left', '<', o.parent_right), ('parent_left', '>=', o.parent_left)]
94                 if prefix:
95                     return [(left, 'in', table.search(cr, uid, doms, context=context))]
96                 return doms
97             else:
98                 def rg(ids, table, parent):
99                     if not ids:
100                         return []
101                     ids2 = table.search(cr, uid, [(parent, 'in', ids)], context=context)
102                     return ids + rg(ids2, table, parent)
103                 return [(left, 'in', rg(ids, table, parent or table._parent_name))]
104
105         self.__main_table = table
106
107         i = -1
108         while i + 1<len(self.__exp):
109             i += 1
110             e = self.__exp[i]
111             if self._is_operator(e) or e == self.__DUMMY_LEAF:
112                 continue
113             left, operator, right = e
114             working_table = table
115             main_table = table
116             fargs = left.split('.', 1)
117             index = i
118             if left in table._inherit_fields:
119                 while True:
120                     field = main_table._columns.get(fargs[0], False)
121                     if field:
122                         working_table = main_table
123                         self.__tables[i] = working_table
124                         break
125                     working_table = main_table.pool.get(main_table._inherit_fields[left][0])
126                     if working_table not in self.__tables.values():
127                         self.__joins.append(('%s.%s=%s.%s' % (working_table._table, 'id', main_table._table, main_table._inherits[working_table._name]), working_table._table))
128                         self.__tables[index] = working_table
129                         index += 1
130                     main_table = working_table
131             
132             field = working_table._columns.get(fargs[0], False)
133             if not field:
134                 if left == 'id' and operator == 'child_of':
135                     dom = _rec_get(right, working_table)
136                     self.__exp = self.__exp[:i] + dom + self.__exp[i+1:]
137                 continue
138
139             field_obj = table.pool.get(field._obj)
140             if len(fargs) > 1:
141                 if field._type == 'many2one':
142                     right = field_obj.search(cr, uid, [(fargs[1], operator, right)], context=context)
143                     self.__exp[i] = (fargs[0], 'in', right)
144                 # Making search easier when there is a left operand as field.o2m or field.m2m
145                 if field._type in ['many2many','one2many']:
146                     right = field_obj.search(cr, uid, [(fargs[1], operator, right)], context=context)
147                     right1 = table.search(cr, uid, [(fargs[0],'in', right)], context=context)
148                     self.__exp[i] = ('id', 'in', right1)                    
149                 
150                 continue
151
152             if field._properties:
153                 # this is a function field
154                 if not field.store:
155                     if not field._fnct_search:
156                         # the function field doesn't provide a search function and doesn't store
157                         # values in the database, so we must ignore it : we generate a dummy leaf
158                         self.__exp[i] = self.__DUMMY_LEAF
159                     else:
160                         subexp = field.search(cr, uid, table, left, [self.__exp[i]], context=context)
161                         # we assume that the expression is valid
162                         # we create a dummy leaf for forcing the parsing of the resulting expression
163                         self.__exp[i] = '&'
164                         self.__exp.insert(i + 1, self.__DUMMY_LEAF)
165                         for j, se in enumerate(subexp):
166                             self.__exp.insert(i + 2 + j, se)
167
168                 # else, the value of the field is store in the database, so we search on it
169
170
171             elif field._type == 'one2many':
172                 # Applying recursivity on field(one2many)
173                 if operator == 'child_of':
174                     if isinstance(right, basestring):
175                         ids2 = [x[0] for x in field_obj.name_search(cr, uid, right, [], 'like', context=context, limit=None)]
176                     else:
177                         ids2 = list(right)
178                     if field._obj != working_table._name:
179                         dom = _rec_get(ids2, field_obj, left=left, prefix=field._obj)
180                     else:
181                         dom = _rec_get(ids2, working_table, parent=left)
182                     self.__exp = self.__exp[:i] + dom + self.__exp[i+1:]
183                 
184                 else:    
185                     call_null = True
186                     
187                     if right:
188                         if isinstance(right, basestring):
189                             ids2 = [x[0] for x in field_obj.name_search(cr, uid, right, [], operator, context=context, limit=None)]
190                             operator = 'in' 
191                         else:
192                             if not isinstance(right,list):
193                                 ids2 = [right]
194                             else:
195                                 ids2 = right    
196                         if not ids2:
197                             call_null = True
198                             operator = 'in' # operator changed because ids are directly related to main object
199                         else:
200                             call_null = False
201                             o2m_op = 'in'
202                             if operator in  ['not like','not ilike','not in','<>','!=']:
203                                 o2m_op = 'not in'
204                             self.__exp[i] = ('id', o2m_op, self.__execute_recursive_in(cr, field._fields_id, field_obj._table, 'id', ids2, operator, field._type))
205                     
206                     if call_null:
207                         o2m_op = 'not in'
208                         if operator in  ['not like','not ilike','not in','<>','!=']:
209                             o2m_op = 'in'                         
210                         self.__exp[i] = ('id', o2m_op, self.__execute_recursive_in(cr, field._fields_id, field_obj._table, 'id', [], operator, field._type) or [0])      
211
212             elif field._type == 'many2many':
213                 #FIXME
214                 if operator == 'child_of':
215                     if isinstance(right, basestring):
216                         ids2 = [x[0] for x in field_obj.name_search(cr, uid, right, [], 'like', context=context, limit=None)]
217                     else:
218                         ids2 = list(right)
219
220                     def _rec_convert(ids):
221                         if field_obj == table:
222                             return ids
223                         return self.__execute_recursive_in(cr, field._id1, field._rel, field._id2, ids, operator, field._type)
224
225                     dom = _rec_get(ids2, field_obj)
226                     ids2 = field_obj.search(cr, uid, dom, context=context)
227                     self.__exp[i] = ('id', 'in', _rec_convert(ids2))
228                 else:
229                     call_null_m2m = True
230                     if right:
231                         if isinstance(right, basestring):
232                             res_ids = [x[0] for x in field_obj.name_search(cr, uid, right, [], operator, context=context)]
233                             operator = 'in'
234                         else:
235                             if not isinstance(right, list):
236                                 res_ids = [right]
237                             else:
238                                 res_ids = right
239                         if not res_ids:
240                             call_null_m2m = True
241                             operator = 'in' # operator changed because ids are directly related to main object
242                         else:
243                             call_null_m2m = False
244                             m2m_op = 'in'        
245                             if operator in  ['not like','not ilike','not in','<>','!=']:
246                                 m2m_op = 'not in'
247                             
248                             self.__exp[i] = ('id', m2m_op, self.__execute_recursive_in(cr, field._id1, field._rel, field._id2, res_ids, operator, field._type) or [0])
249                     if call_null_m2m:
250                         m2m_op = 'not in'
251                         if operator in  ['not like','not ilike','not in','<>','!=']:
252                             m2m_op = 'in'                         
253                         self.__exp[i] = ('id', m2m_op, self.__execute_recursive_in(cr, field._id1, field._rel, field._id2, [], operator,  field._type) or [0])
254                         
255             elif field._type == 'many2one':
256                 if operator == 'child_of':
257                     if isinstance(right, basestring):
258                         ids2 = [x[0] for x in field_obj.name_search(cr, uid, right, [], 'like', limit=None)]
259                     else:
260                         ids2 = list(right)
261
262                     self.__operator = 'in'
263                     if field._obj != working_table._name:
264                         dom = _rec_get(ids2, field_obj, left=left, prefix=field._obj)
265                     else:
266                         dom = _rec_get(ids2, working_table, parent=left)
267                     self.__exp = self.__exp[:i] + dom + self.__exp[i+1:]
268                 else:
269                     if isinstance(right, basestring): # and not isinstance(field, fields.related):
270                         c = context.copy()
271                         c['active_test'] = False
272                         res_ids = field_obj.name_search(cr, uid, right, [], operator, limit=None, context=c)
273                         right = map(lambda x: x[0], res_ids)
274                         self.__exp[i] = (left, 'in', right)
275             else:
276                 # other field type
277                 # add the time part to datetime field when it's not there:
278                 if field._type == 'datetime' and self.__exp[i][2] and len(self.__exp[i][2]) == 10:
279                     
280                     self.__exp[i] = list(self.__exp[i])
281                     
282                     if operator in ('>', '>='):
283                         self.__exp[i][2] += ' 00:00:00'
284                     elif operator in ('<', '<='):
285                         self.__exp[i][2] += ' 23:59:59'
286                     
287                     self.__exp[i] = tuple(self.__exp[i])
288                         
289                 if field.translate:
290                     if operator in ('like', 'ilike', 'not like', 'not ilike'):
291                         right = '%%%s%%' % right
292
293                     operator = operator == '=like' and 'like' or operator
294
295                     query1 = '( SELECT res_id'          \
296                              '    FROM ir_translation'  \
297                              '   WHERE name = %s'       \
298                              '     AND lang = %s'       \
299                              '     AND type = %s'
300                     instr = ' %s'
301                     #Covering in,not in operators with operands (%s,%s) ,etc.
302                     if operator in ['in','not in']:
303                         instr = ','.join(['%s'] * len(right))
304                         query1 += '     AND value ' + operator +  ' ' +" (" + instr + ")"   \
305                              ') UNION ('                \
306                              '  SELECT id'              \
307                              '    FROM "' + working_table._table + '"'       \
308                              '   WHERE "' + left + '" ' + operator + ' ' +" (" + instr + "))"
309                     else:
310                         query1 += '     AND value ' + operator + instr +   \
311                              ') UNION ('                \
312                              '  SELECT id'              \
313                              '    FROM "' + working_table._table + '"'       \
314                              '   WHERE "' + left + '" ' + operator + instr + ")"
315
316                     query2 = [working_table._name + ',' + left,
317                               context.get('lang', False) or 'en_US',
318                               'model',
319                               right,
320                               right,
321                              ]
322
323                     self.__exp[i] = ('id', 'inselect', (query1, query2))
324
325         return self
326
327     def __leaf_to_sql(self, leaf, table):
328         if leaf == self.__DUMMY_LEAF:
329             return ('(1=1)', [])
330         left, operator, right = leaf
331
332         if operator == 'inselect':
333             query = '(%s.%s in (%s))' % (table._table, left, right[0])
334             params = right[1]
335         elif operator in ['in', 'not in']:
336             params = right and right[:] or []
337             len_before = len(params)
338             for i in range(len_before)[::-1]:
339                 if params[i] == False:
340                     del params[i]
341
342             len_after = len(params)
343             check_nulls = len_after != len_before
344             query = '(1=0)'
345             
346             if len_after:
347                 if left == 'id':
348                     instr = ','.join(['%s'] * len_after)
349                 else:
350                     instr = ','.join([table._columns[left]._symbol_set[0]] * len_after)
351                 query = '(%s.%s %s (%s))' % (table._table, left, operator, instr)
352             else:
353                 # the case for [field, 'in', []] or [left, 'not in', []]
354                 if operator == 'in':
355                     query = '(%s.%s IS NULL)' % (table._table, left)
356                 else:
357                     query = '(%s.%s IS NOT NULL)' % (table._table, left)
358             if check_nulls:
359                 query = '(%s OR %s.%s IS NULL)' % (query, table._table, left)
360         else:
361             params = []
362             
363             if right == False and (leaf[0] in table._columns)  and table._columns[leaf[0]]._type=="boolean"  and (operator == '='):
364                 query = '(%s.%s IS NULL or %s.%s = false )' % (table._table, left,table._table, left)
365             elif (((right == False) and (type(right)==bool)) or (right is None)) and (operator == '='):
366                 query = '%s.%s IS NULL ' % (table._table, left)
367             elif right == False and (leaf[0] in table._columns)  and table._columns[leaf[0]]._type=="boolean"  and (operator in ['<>', '!=']):
368                 query = '(%s.%s IS NOT NULL and %s.%s != false)' % (table._table, left,table._table, left)
369             elif (((right == False) and (type(right)==bool)) or right is None) and (operator in ['<>', '!=']):
370                 query = '%s.%s IS NOT NULL' % (table._table, left)
371             else:
372                 if left == 'id':
373                     query = '%s.id %s %%s' % (table._table, operator)
374                     params = right
375                 else:
376                     like = operator in ('like', 'ilike', 'not like', 'not ilike')
377
378                     op = operator == '=like' and 'like' or operator
379                     if left in table._columns:
380                         format = like and '%s' or table._columns[left]._symbol_set[0]
381                         query = '(%s.%s %s %s)' % (table._table, left, op, format)
382                     else:
383                         query = "(%s.%s %s '%s')" % (table._table, left, op, right)
384
385                     add_null = False
386                     if like:
387                         if isinstance(right, str):
388                             str_utf8 = right
389                         elif isinstance(right, unicode):
390                             str_utf8 = right.encode('utf-8')
391                         else:
392                             str_utf8 = str(right)
393                         params = '%%%s%%' % str_utf8
394                         add_null = not str_utf8
395                     elif left in table._columns:
396                         params = table._columns[left]._symbol_set[1](right)
397
398                     if add_null:
399                         query = '(%s OR %s IS NULL)' % (query, left)
400
401         if isinstance(params, basestring):
402             params = [params]
403         return (query, params)
404
405
406     def to_sql(self):
407         stack = []
408         params = []
409         for i, e in reverse_enumerate(self.__exp):
410             if self._is_leaf(e, internal=True):
411                 table = self.__tables.get(i, self.__main_table)
412                 q, p = self.__leaf_to_sql(e, table)
413                 params.insert(0, p)
414                 stack.append(q)
415             else:
416                 if e == '!':
417                     stack.append('(NOT (%s))' % (stack.pop(),))
418                 else:
419                     ops = {'&': ' AND ', '|': ' OR '}
420                     q1 = stack.pop()
421                     q2 = stack.pop()
422                     stack.append('(%s %s %s)' % (q1, ops[e], q2,))
423
424         query = ' AND '.join(reversed(stack))
425         joins = ' AND '.join(map(lambda j: j[0], self.__joins))
426         if joins:
427             query = '(%s) AND (%s)' % (joins, query)
428         return (query, flatten(params))
429
430     def get_tables(self):
431         return ['"%s"' % t._table for t in set(self.__tables.values()+[self.__main_table])]
432
433 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
434