[FIX] recursive calls
[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 not ids:
50             return []
51         if op not in ('<','>','=','>=','<=','not in'):
52             op = 'in'
53         for i in range(0, len(ids), cr.IN_MAX):
54             subids = ids[i:i+cr.IN_MAX]
55             cr.execute('SELECT "%s"'    \
56                        ' FROM "%s"'    \
57                        ' WHERE "%s" %s (%s)' % (s, f, w, op, ','.join(['%s']*len(subids))),
58                        subids)
59             res += [r[0] for r in cr.fetchall() if r[0]]
60         return res + (res and self.__execute_recursive_in(cr, s, f, w, res, op, type) or [])
61
62     def __init__(self, exp):
63         # check if the expression is valid
64         if not reduce(lambda acc, val: acc and (self._is_operator(val) or self._is_leaf(val)), exp, True):
65             raise ValueError('Bad domain expression: %r' % (exp,))
66         self.__exp = exp
67         self.__tables = {}  # used to store the table to use for the sql generation. key = index of the leaf
68         self.__joins = []
69         self.__main_table = None # 'root' table. set by parse()
70         self.__DUMMY_LEAF = (1, '=', 1) # a dummy leaf that must not be parsed or sql generated
71
72
73     def parse(self, cr, uid, table, context):
74         """ transform the leafs of the expression """
75         if not self.__exp:
76             return self
77
78         def _rec_get(ids, table, parent=None, left='id', prefix=''):
79             if table._parent_store and (not table.pool._init):
80 # TODO: Improve where joins are implemented for many with '.', replace by:
81 # doms += ['&',(prefix+'.parent_left','<',o.parent_right),(prefix+'.parent_left','>=',o.parent_left)]
82                 doms = []
83                 for o in table.browse(cr, uid, ids, context=context):
84                     if doms:
85                         doms.insert(0, '|')
86                     doms += ['&', ('parent_left', '<', o.parent_right), ('parent_left', '>=', o.parent_left)]
87                 if prefix:
88                     return [(left, 'in', table.search(cr, uid, doms, context=context))]
89                 return doms
90             else:
91                 def rg(ids, table, parent):
92                     if not ids:
93                         return []
94                     ids2 = table.search(cr, uid, [(parent, 'in', ids)], context=context)
95                     return ids + rg(ids2, table, parent)
96                 return [(left, 'in', rg(ids, table, parent or table._parent_name))]
97
98         self.__main_table = table
99
100         i = -1
101         while i + 1<len(self.__exp):
102             i += 1
103             e = self.__exp[i]
104             if self._is_operator(e) or e == self.__DUMMY_LEAF:
105                 continue
106             left, operator, right = e
107             working_table = table
108             main_table = table
109             fargs = left.split('.', 1)
110             index = i
111             if left in table._inherit_fields:
112                 while True:
113                     field = main_table._columns.get(fargs[0], False)
114                     if field:
115                         working_table = main_table
116                         self.__tables[i] = working_table
117                         break
118                     working_table = main_table.pool.get(main_table._inherit_fields[left][0])
119                     if working_table not in self.__tables.values():
120                         self.__joins.append(('%s.%s=%s.%s' % (working_table._table, 'id', main_table._table, main_table._inherits[working_table._name]), working_table._table))
121                         self.__tables[index] = working_table
122                         index += 1
123                     main_table = working_table
124             
125             field = working_table._columns.get(fargs[0], False)
126             if not field:
127                 if left == 'id' and operator == 'child_of':
128                     dom = _rec_get(right, working_table)
129                     self.__exp = self.__exp[:i] + dom + self.__exp[i+1:]
130                 continue
131
132             field_obj = table.pool.get(field._obj)
133             if len(fargs) > 1:
134                 if field._type == 'many2one':
135                     right = field_obj.search(cr, uid, [(fargs[1], operator, right)], context=context)
136                     self.__exp[i] = (fargs[0], 'in', right)
137                 continue
138
139             if field._properties:
140                 # this is a function field
141                 if not field.store:
142                     if not field._fnct_search:
143                         # the function field doesn't provide a search function and doesn't store
144                         # values in the database, so we must ignore it : we generate a dummy leaf
145                         self.__exp[i] = self.__DUMMY_LEAF
146                     else:
147                         subexp = field.search(cr, uid, table, left, [self.__exp[i]])
148                         # we assume that the expression is valid
149                         # we create a dummy leaf for forcing the parsing of the resulting expression
150                         self.__exp[i] = '&'
151                         self.__exp.insert(i + 1, self.__DUMMY_LEAF)
152                         for j, se in enumerate(subexp):
153                             self.__exp.insert(i + 2 + j, se)
154
155                 # else, the value of the field is store in the database, so we search on it
156
157
158             elif field._type == 'one2many':
159                 call_null = True
160                 
161                 if right:
162                     if isinstance(right, basestring):
163                         ids2 = [x[0] for x in field_obj.name_search(cr, uid, right, [], operator, limit=None)]
164                         operator = 'in' 
165                     else:
166                         if not isinstance(right,list):
167                             ids2 = [right]
168                         else:
169                             ids2 = right    
170                     if not ids2:
171                         call_null = True
172                         operator = 'in' # operator changed because ids are directly related to main object
173                     else:
174                         call_null = False
175                         o2m_op = 'in'
176                         if operator in  ['not like','not ilike','not in','<>','!=']:
177                             o2m_op = 'not in'
178                         self.__exp[i] = ('id', o2m_op, self.__execute_recursive_in(cr, field._fields_id, field_obj._table, 'id', ids2, operator, field._type))
179                 
180                 if call_null:
181                     o2m_op = 'not in'
182                     if operator in  ['not like','not ilike','not in','<>','!=']:
183                         o2m_op = 'in'                         
184                     self.__exp[i] = ('id', o2m_op, self.__execute_recursive_in(cr, field._fields_id, field_obj._table, 'id', [], operator, field._type) or [0])      
185
186             elif field._type == 'many2many':
187                 #FIXME
188                 if operator == 'child_of':
189                     if isinstance(right, basestring):
190                         ids2 = [x[0] for x in field_obj.name_search(cr, uid, right, [], 'like', limit=None)]
191                     else:
192                         ids2 = list(right)
193
194                     def _rec_convert(ids):
195                         if field_obj == table:
196                             return ids
197                         return self.__execute_recursive_in(cr, field._id1, field._rel, field._id2, ids, operator, field._type)
198
199                     dom = _rec_get(ids2, field_obj)
200                     ids2 = field_obj.search(cr, uid, dom, context=context)
201                     self.__exp[i] = ('id', 'in', _rec_convert(ids2))
202                 else:
203                     call_null_m2m = True
204                     if right:
205                         if isinstance(right, basestring):
206                             res_ids = [x[0] for x in field_obj.name_search(cr, uid, right, [], operator)]
207                             operator = 'in'
208                         else:
209                             if not isinstance(right, list):
210                                 res_ids = [right]
211                             else:
212                                 res_ids = right
213                         if not res_ids:
214                             call_null_m2m = True
215                             operator = 'in' # operator changed because ids are directly related to main object
216                         else:
217                             call_null_m2m = False
218                             m2m_op = 'in'        
219                             if operator in  ['not like','not ilike','not in','<>','!=']:
220                                 m2m_op = 'not in'
221                             
222                             self.__exp[i] = ('id', m2m_op, self.__execute_recursive_in(cr, field._id1, field._rel, field._id2, res_ids, operator, field._type) or [0])
223                     if call_null_m2m:
224                         m2m_op = 'not in'
225                         if operator in  ['not like','not ilike','not in','<>','!=']:
226                             m2m_op = 'in'                         
227                         self.__exp[i] = ('id', m2m_op, self.__execute_recursive_in(cr, field._id1, field._rel, field._id2, [], operator,  field._type) or [0])
228                         
229             elif field._type == 'many2one':
230                 if operator == 'child_of':
231                     if isinstance(right, basestring):
232                         ids2 = [x[0] for x in field_obj.name_search(cr, uid, right, [], 'like', limit=None)]
233                     else:
234                         ids2 = list(right)
235
236                     self.__operator = 'in'
237                     if field._obj != working_table._name:
238                         dom = _rec_get(ids2, field_obj, left=left, prefix=field._obj)
239                     else:
240                         dom = _rec_get(ids2, working_table, parent=left)
241                     self.__exp = self.__exp[:i] + dom + self.__exp[i+1:]
242                 else:
243                     if isinstance(right, basestring): # and not isinstance(field, fields.related):
244                         c = context.copy()
245                         c['active_test'] = False
246                         res_ids = field_obj.name_search(cr, uid, right, [], operator, limit=None, context=c)
247                         right = map(lambda x: x[0], res_ids)
248                         self.__exp[i] = (left, 'in', right)
249             else:
250                 # other field type
251                 # add the time part to datetime field when it's not there:
252                 if field._type == 'datetime' and self.__exp[i][2] and len(self.__exp[i][2]) == 10:
253                     
254                     self.__exp[i] = list(self.__exp[i])
255                     
256                     if operator in ('>', '>='):
257                         self.__exp[i][2] += ' 00:00:00'
258                     elif operator in ('<', '<='):
259                         self.__exp[i][2] += ' 23:59:59'
260                     
261                     self.__exp[i] = tuple(self.__exp[i])
262                         
263                 if field.translate:
264                     if operator in ('like', 'ilike', 'not like', 'not ilike'):
265                         right = '%%%s%%' % right
266
267                     operator = operator == '=like' and 'like' or operator
268
269                     query1 = '( SELECT res_id'          \
270                              '    FROM ir_translation'  \
271                              '   WHERE name = %s'       \
272                              '     AND lang = %s'       \
273                              '     AND type = %s'
274                     instr = ' %s'
275                     #Covering in,not in operators with operands (%s,%s) ,etc.
276                     if operator in ['in','not in']:
277                         instr = ','.join(['%s'] * len(right))
278                         query1 += '     AND value ' + operator +  ' ' +" (" + instr + ")"   \
279                              ') UNION ('                \
280                              '  SELECT id'              \
281                              '    FROM "' + working_table._table + '"'       \
282                              '   WHERE "' + left + '" ' + operator + ' ' +" (" + instr + "))"
283                     else:
284                         query1 += '     AND value ' + operator + instr +   \
285                              ') UNION ('                \
286                              '  SELECT id'              \
287                              '    FROM "' + working_table._table + '"'       \
288                              '   WHERE "' + left + '" ' + operator + instr + ")"
289
290                     query2 = [working_table._name + ',' + left,
291                               context.get('lang', False) or 'en_US',
292                               'model',
293                               right,
294                               right,
295                              ]
296
297                     self.__exp[i] = ('id', 'inselect', (query1, query2))
298
299         return self
300
301     def __leaf_to_sql(self, leaf, table):
302         if leaf == self.__DUMMY_LEAF:
303             return ('(1=1)', [])
304         left, operator, right = leaf
305
306         if operator == 'inselect':
307             query = '(%s.%s in (%s))' % (table._table, left, right[0])
308             params = right[1]
309         elif operator in ['in', 'not in']:
310             params = right[:]
311             len_before = len(params)
312             for i in range(len_before)[::-1]:
313                 if params[i] == False:
314                     del params[i]
315
316             len_after = len(params)
317             check_nulls = len_after != len_before
318             query = '(1=0)'
319
320             if len_after:
321                 if left == 'id':
322                     instr = ','.join(['%s'] * len_after)
323                 else:
324                     instr = ','.join([table._columns[left]._symbol_set[0]] * len_after)
325                 query = '(%s.%s %s (%s))' % (table._table, left, operator, instr)
326
327             if check_nulls:
328                 query = '(%s OR %s.%s IS NULL)' % (query, table._table, left)
329         else:
330             params = []
331             
332             if right == False and (leaf[0] in table._columns)  and table._columns[leaf[0]]._type=="boolean"  and (operator == '='):
333                 query = '(%s.%s IS NULL or %s.%s = false )' % (table._table, left,table._table, left)
334             elif (((right == False) and (type(right)==bool)) or (right is None)) and (operator == '='):
335                 query = '%s.%s IS NULL ' % (table._table, left)
336             elif right == False and (leaf[0] in table._columns)  and table._columns[leaf[0]]._type=="boolean"  and (operator in ['<>', '!=']):
337                 query = '(%s.%s IS NOT NULL and %s.%s != false)' % (table._table, left,table._table, left)
338             elif (((right == False) and (type(right)==bool)) or right is None) and (operator in ['<>', '!=']):
339                 query = '%s.%s IS NOT NULL' % (table._table, left)
340             else:
341                 if left == 'id':
342                     query = '%s.id %s %%s' % (table._table, operator)
343                     params = right
344                 else:
345                     like = operator in ('like', 'ilike', 'not like', 'not ilike')
346
347                     op = operator == '=like' and 'like' or operator
348                     if left in table._columns:
349                         format = like and '%s' or table._columns[left]._symbol_set[0]
350                         query = '(%s.%s %s %s)' % (table._table, left, op, format)
351                     else:
352                         query = "(%s.%s %s '%s')" % (table._table, left, op, right)
353
354                     add_null = False
355                     if like:
356                         if isinstance(right, str):
357                             str_utf8 = right
358                         elif isinstance(right, unicode):
359                             str_utf8 = right.encode('utf-8')
360                         else:
361                             str_utf8 = str(right)
362                         params = '%%%s%%' % str_utf8
363                         add_null = not str_utf8
364                     elif left in table._columns:
365                         params = table._columns[left]._symbol_set[1](right)
366
367                     if add_null:
368                         query = '(%s OR %s IS NULL)' % (query, left)
369
370         if isinstance(params, basestring):
371             params = [params]
372         return (query, params)
373
374
375     def to_sql(self):
376         stack = []
377         params = []
378         for i, e in reverse_enumerate(self.__exp):
379             if self._is_leaf(e, internal=True):
380                 table = self.__tables.get(i, self.__main_table)
381                 q, p = self.__leaf_to_sql(e, table)
382                 params.insert(0, p)
383                 stack.append(q)
384             else:
385                 if e == '!':
386                     stack.append('(NOT (%s))' % (stack.pop(),))
387                 else:
388                     ops = {'&': ' AND ', '|': ' OR '}
389                     q1 = stack.pop()
390                     q2 = stack.pop()
391                     stack.append('(%s %s %s)' % (q1, ops[e], q2,))
392
393         query = ' AND '.join(reversed(stack))
394         joins = ' AND '.join(map(lambda j: j[0], self.__joins))
395         if joins:
396             query = '(%s) AND (%s)' % (joins, query)
397         return (query, flatten(params))
398
399     def get_tables(self):
400         return ['"%s"' % t._table for t in set(self.__tables.values()+[self.__main_table])]
401
402 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
403