9303f35ef21d279300b70e23c32956dfacf96b8b
[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),
61                                (tuple(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.__field_tables = {}  # used to store the table to use for the sql generation. key = index of the leaf
75         self.__all_tables = set()
76         self.__joins = []
77         self.__main_table = None # 'root' table. set by parse()
78         self.__DUMMY_LEAF = (1, '=', 1) # a dummy leaf that must not be parsed or sql generated
79
80
81     def parse(self, cr, uid, table, context):
82         """ transform the leafs of the expression """
83         if not self.__exp:
84             return self
85
86         def _rec_get(ids, table, parent=None, left='id', prefix=''):
87             if table._parent_store and (not table.pool._init):
88 # TODO: Improve where joins are implemented for many with '.', replace by:
89 # doms += ['&',(prefix+'.parent_left','<',o.parent_right),(prefix+'.parent_left','>=',o.parent_left)]
90                 doms = []
91                 for o in table.browse(cr, uid, ids, context=context):
92                     if doms:
93                         doms.insert(0, '|')
94                     doms += ['&', ('parent_left', '<', o.parent_right), ('parent_left', '>=', o.parent_left)]
95                 if prefix:
96                     return [(left, 'in', table.search(cr, uid, doms, context=context))]
97                 return doms
98             else:
99                 def rg(ids, table, parent):
100                     if not ids:
101                         return []
102                     ids2 = table.search(cr, uid, [(parent, 'in', ids)], context=context)
103                     return ids + rg(ids2, table, parent)
104                 return [(left, 'in', rg(ids, table, parent or table._parent_name))]
105
106         self.__main_table = table
107         self.__all_tables.add(table)
108
109         i = -1
110         while i + 1<len(self.__exp):
111             i += 1
112             e = self.__exp[i]
113             if self._is_operator(e) or e == self.__DUMMY_LEAF:
114                 continue
115             left, operator, right = e
116             operator = operator.lower()
117             working_table = table
118             main_table = table
119             fargs = left.split('.', 1)
120             if left in table._inherit_fields:
121                 while True:
122                     field = main_table._columns.get(fargs[0], False)
123                     if field:
124                         working_table = main_table
125                         self.__field_tables[i] = working_table
126                         break
127                     working_table = main_table.pool.get(main_table._inherit_fields[left][0])
128                     if working_table not in self.__all_tables:
129                         self.__joins.append(('%s.%s=%s.%s' % (working_table._table, 'id', main_table._table, main_table._inherits[working_table._name]), working_table._table))
130                         self.__all_tables.add(working_table)
131                     main_table = working_table
132             
133             field = working_table._columns.get(fargs[0], False)
134             if not field:
135                 if left == 'id' and operator == 'child_of':
136                     dom = _rec_get(right, working_table)
137                     self.__exp = self.__exp[:i] + dom + self.__exp[i+1:]
138                 continue
139
140             field_obj = table.pool.get(field._obj)
141             if len(fargs) > 1:
142                 if field._type == 'many2one':
143                     right = field_obj.search(cr, uid, [(fargs[1], operator, right)], context=context)
144                     self.__exp[i] = (fargs[0], 'in', right)
145                 # Making search easier when there is a left operand as field.o2m or field.m2m
146                 if field._type in ['many2many','one2many']:
147                     right = field_obj.search(cr, uid, [(fargs[1], operator, right)], context=context)
148                     right1 = table.search(cr, uid, [(fargs[0],'in', right)], context=context)
149                     self.__exp[i] = ('id', 'in', right1)                    
150                 
151                 if not isinstance(field,fields.property):
152                     continue
153
154             if field._properties and not field.store:
155
156                 # this is a function field which is not stored.
157                 if not field._fnct_search:
158                     # the function field doesn't provide a search function and doesn't store
159                     # values in the database, so we must ignore it : we generate a dummy leaf
160                     self.__exp[i] = self.__DUMMY_LEAF
161                 else:
162                     subexp = field.search(cr, uid, table, left, [self.__exp[i]], context=context)
163                     # we assume that the expression is valid
164                     # we create a dummy leaf for forcing the parsing of the resulting expression
165                     self.__exp[i] = '&'
166                     self.__exp.insert(i + 1, self.__DUMMY_LEAF)
167                     for j, se in enumerate(subexp):
168                         self.__exp.insert(i + 2 + j, se)
169
170                 # else, the value of the field is store in the database, so we search on it
171
172
173             elif field._type == 'one2many':
174                 # Applying recursivity on field(one2many)
175                 if operator == 'child_of':
176                     if isinstance(right, basestring):
177                         ids2 = [x[0] for x in field_obj.name_search(cr, uid, right, [], 'like', context=context, limit=None)]
178                     else:
179                         ids2 = list(right)
180                     if field._obj != working_table._name:
181                         dom = _rec_get(ids2, field_obj, left=left, prefix=field._obj)
182                     else:
183                         dom = _rec_get(ids2, working_table, parent=left)
184                     self.__exp = self.__exp[:i] + dom + self.__exp[i+1:]
185                 
186                 else:    
187                     call_null = True
188                     
189                     if right:
190                         if isinstance(right, basestring):
191                             ids2 = [x[0] for x in field_obj.name_search(cr, uid, right, [], operator, context=context, limit=None)]
192                             if ids2:
193                                 operator = 'in' 
194                         else:
195                             if not isinstance(right,list):
196                                 ids2 = [right]
197                             else:
198                                 ids2 = right    
199                         if not ids2:
200                             if operator in ['like','ilike','in','=']:
201                                 #no result found with given search criteria
202                                 call_null = False
203                                 self.__exp[i] = ('id','=',0)
204                             else:
205                                 call_null = True
206                                 operator = 'in' # operator changed because ids are directly related to main object
207                         else:
208                             call_null = False
209                             o2m_op = 'in'
210                             if operator in  ['not like','not ilike','not in','<>','!=']:
211                                 o2m_op = 'not in'
212                             self.__exp[i] = ('id', o2m_op, self.__execute_recursive_in(cr, field._fields_id, field_obj._table, 'id', ids2, operator, field._type))
213                     
214                     if call_null:
215                         o2m_op = 'not in'
216                         if operator in  ['not like','not ilike','not in','<>','!=']:
217                             o2m_op = 'in'                         
218                         self.__exp[i] = ('id', o2m_op, self.__execute_recursive_in(cr, field._fields_id, field_obj._table, 'id', [], operator, field._type) or [0])      
219
220             elif field._type == 'many2many':
221                 #FIXME
222                 if operator == 'child_of':
223                     if isinstance(right, basestring):
224                         ids2 = [x[0] for x in field_obj.name_search(cr, uid, right, [], 'like', context=context, limit=None)]
225                     else:
226                         ids2 = list(right)
227
228                     def _rec_convert(ids):
229                         if field_obj == table:
230                             return ids
231                         return self.__execute_recursive_in(cr, field._id1, field._rel, field._id2, ids, operator, field._type)
232
233                     dom = _rec_get(ids2, field_obj)
234                     ids2 = field_obj.search(cr, uid, dom, context=context)
235                     self.__exp[i] = ('id', 'in', _rec_convert(ids2))
236                 else:
237                     call_null_m2m = True
238                     if right:
239                         if isinstance(right, basestring):
240                             res_ids = [x[0] for x in field_obj.name_search(cr, uid, right, [], operator, context=context)]
241                             if res_ids:
242                                 operator = 'in'
243                         else:
244                             if not isinstance(right, list):
245                                 res_ids = [right]
246                             else:
247                                 res_ids = right
248                         if not res_ids:
249                             if operator in ['like','ilike','in','=']:
250                                 #no result found with given search criteria
251                                 call_null_m2m = False
252                                 self.__exp[i] = ('id','=',0)
253                             else: 
254                                 call_null_m2m = True
255                                 operator = 'in' # operator changed because ids are directly related to main object
256                         else:
257                             call_null_m2m = False
258                             m2m_op = 'in'        
259                             if operator in  ['not like','not ilike','not in','<>','!=']:
260                                 m2m_op = 'not in'
261                             
262                             self.__exp[i] = ('id', m2m_op, self.__execute_recursive_in(cr, field._id1, field._rel, field._id2, res_ids, operator, field._type) or [0])
263                     if call_null_m2m:
264                         m2m_op = 'not in'
265                         if operator in  ['not like','not ilike','not in','<>','!=']:
266                             m2m_op = 'in'                         
267                         self.__exp[i] = ('id', m2m_op, self.__execute_recursive_in(cr, field._id1, field._rel, field._id2, [], operator,  field._type) or [0])
268
269             elif field._type == 'many2one':
270                 if operator == 'child_of':
271                     if isinstance(right, basestring):
272                         ids2 = [x[0] for x in field_obj.name_search(cr, uid, right, [], 'like', limit=None)]
273                     else:
274                         ids2 = list(right)
275
276                     self.__operator = 'in'
277                     if field._obj != working_table._name:
278                         dom = _rec_get(ids2, field_obj, left=left, prefix=field._obj)
279                     else:
280                         dom = _rec_get(ids2, working_table, parent=left)
281                     self.__exp = self.__exp[:i] + dom + self.__exp[i+1:]
282                 else:
283                     
284                     def _get_expression(field_obj,cr, uid, left, right, operator, context=None):
285                         if context is None:
286                             context = {}
287                         c = context.copy()
288                         c['active_test'] = False
289                         #Special treatment to ill-formed domains
290                         operator = ( operator in ['<','>','<=','>='] ) and 'in' or operator
291                         
292                         dict_op = {'not in':'!=','in':'=','=':'in','!=':'not in','<>':'not in'}
293                         if isinstance(right,tuple):
294                             right = list(right)
295                         if (not isinstance(right,list)) and operator in ['not in','in']:
296                             operator = dict_op[operator]
297                         elif isinstance(right,list) and operator in ['<>','!=','=']: #for domain (FIELD,'=',['value1','value2'])
298                             operator = dict_op[operator]
299                         res_ids = field_obj.name_search(cr, uid, right, [], operator, limit=None, context=c)
300                         if not res_ids:
301                              return ('id','=',0)
302                         else:
303                             right = map(lambda x: x[0], res_ids)
304                             return (left, 'in', right)
305
306                     m2o_str = False
307                     if right:
308                         if isinstance(right, basestring): # and not isinstance(field, fields.related):
309                             m2o_str = True
310                         elif isinstance(right,(list,tuple)):
311                             m2o_str = True
312                             for ele in right:
313                                 if not isinstance(ele, basestring): 
314                                     m2o_str = False
315                                     break
316                     else:
317                         new_op = '='
318                         if operator in  ['not like','not ilike','not in','<>','!=']:
319                             new_op = '!='
320                         #Is it ok to put 'left' and not 'id' ?
321                         self.__exp[i] = (left,new_op,False)
322
323                     if m2o_str:
324                         self.__exp[i] = _get_expression(field_obj,cr, uid, left, right, operator, context=context)
325             else:
326                 # other field type
327                 # add the time part to datetime field when it's not there:
328                 if field._type == 'datetime' and self.__exp[i][2] and len(self.__exp[i][2]) == 10:
329                     
330                     self.__exp[i] = list(self.__exp[i])
331                     
332                     if operator in ('>', '>='):
333                         self.__exp[i][2] += ' 00:00:00'
334                     elif operator in ('<', '<='):
335                         self.__exp[i][2] += ' 23:59:59'
336                     
337                     self.__exp[i] = tuple(self.__exp[i])
338                         
339                 if field.translate:
340                     if operator in ('like', 'ilike', 'not like', 'not ilike'):
341                         right = '%%%s%%' % right
342
343                     operator = operator == '=like' and 'like' or operator
344
345                     query1 = '( SELECT res_id'          \
346                              '    FROM ir_translation'  \
347                              '   WHERE name = %s'       \
348                              '     AND lang = %s'       \
349                              '     AND type = %s'
350                     instr = ' %s'
351                     #Covering in,not in operators with operands (%s,%s) ,etc.
352                     if operator in ['in','not in']:
353                         instr = ','.join(['%s'] * len(right))
354                         query1 += '     AND value ' + operator +  ' ' +" (" + instr + ")"   \
355                              ') UNION ('                \
356                              '  SELECT id'              \
357                              '    FROM "' + working_table._table + '"'       \
358                              '   WHERE "' + left + '" ' + operator + ' ' +" (" + instr + "))"
359                     else:
360                         query1 += '     AND value ' + operator + instr +   \
361                              ') UNION ('                \
362                              '  SELECT id'              \
363                              '    FROM "' + working_table._table + '"'       \
364                              '   WHERE "' + left + '" ' + operator + instr + ")"
365
366                     query2 = [working_table._name + ',' + left,
367                               context.get('lang', False) or 'en_US',
368                               'model',
369                               right,
370                               right,
371                              ]
372
373                     self.__exp[i] = ('id', 'inselect', (query1, query2))
374
375         return self
376
377     def __leaf_to_sql(self, leaf, table):
378         if leaf == self.__DUMMY_LEAF:
379             return ('(1=1)', [])
380         left, operator, right = leaf
381
382         if operator == 'inselect':
383             query = '(%s.%s in (%s))' % (table._table, left, right[0])
384             params = right[1]
385         elif operator in ['in', 'not in']:
386             params = right and right[:] or []
387             len_before = len(params)
388             for i in range(len_before)[::-1]:
389                 if params[i] == False:
390                     del params[i]
391
392             len_after = len(params)
393             check_nulls = len_after != len_before
394             query = '(1=0)'
395             
396             if len_after:
397                 if left == 'id':
398                     instr = ','.join(['%s'] * len_after)
399                 else:
400                     instr = ','.join([table._columns[left]._symbol_set[0]] * len_after)
401                 query = '(%s.%s %s (%s))' % (table._table, left, operator, instr)
402             else:
403                 # the case for [field, 'in', []] or [left, 'not in', []]
404                 if operator == 'in':
405                     query = '(%s.%s IS NULL)' % (table._table, left)
406                 else:
407                     query = '(%s.%s IS NOT NULL)' % (table._table, left)
408             if check_nulls:
409                 query = '(%s OR %s.%s IS NULL)' % (query, table._table, left)
410         else:
411             params = []
412             
413             if right == False and (leaf[0] in table._columns)  and table._columns[leaf[0]]._type=="boolean"  and (operator == '='):
414                 query = '(%s.%s IS NULL or %s.%s = false )' % (table._table, left,table._table, left)
415             elif (((right == False) and (type(right)==bool)) or (right is None)) and (operator == '='):
416                 query = '%s.%s IS NULL ' % (table._table, left)
417             elif right == False and (leaf[0] in table._columns)  and table._columns[leaf[0]]._type=="boolean"  and (operator in ['<>', '!=']):
418                 query = '(%s.%s IS NOT NULL and %s.%s != false)' % (table._table, left,table._table, left)
419             elif (((right == False) and (type(right)==bool)) or right is None) and (operator in ['<>', '!=']):
420                 query = '%s.%s IS NOT NULL' % (table._table, left)
421             else:
422                 if left == 'id':
423                     query = '%s.id %s %%s' % (table._table, operator)
424                     params = right
425                 else:
426                     like = operator in ('like', 'ilike', 'not like', 'not ilike')
427
428                     op = operator == '=like' and 'like' or operator
429                     if left in table._columns:
430                         format = like and '%s' or table._columns[left]._symbol_set[0]
431                         query = '(%s.%s %s %s)' % (table._table, left, op, format)
432                     else:
433                         query = "(%s.%s %s '%s')" % (table._table, left, op, right)
434
435                     add_null = False
436                     if like:
437                         if isinstance(right, str):
438                             str_utf8 = right
439                         elif isinstance(right, unicode):
440                             str_utf8 = right.encode('utf-8')
441                         else:
442                             str_utf8 = str(right)
443                         params = '%%%s%%' % str_utf8
444                         add_null = not str_utf8
445                     elif left in table._columns:
446                         params = table._columns[left]._symbol_set[1](right)
447
448                     if add_null:
449                         query = '(%s OR %s IS NULL)' % (query, left)
450
451         if isinstance(params, basestring):
452             params = [params]
453         return (query, params)
454
455
456     def to_sql(self):
457         stack = []
458         params = []
459         for i, e in reverse_enumerate(self.__exp):
460             if self._is_leaf(e, internal=True):
461                 table = self.__field_tables.get(i, self.__main_table)
462                 q, p = self.__leaf_to_sql(e, table)
463                 params.insert(0, p)
464                 stack.append(q)
465             else:
466                 if e == '!':
467                     stack.append('(NOT (%s))' % (stack.pop(),))
468                 else:
469                     ops = {'&': ' AND ', '|': ' OR '}
470                     q1 = stack.pop()
471                     q2 = stack.pop()
472                     stack.append('(%s %s %s)' % (q1, ops[e], q2,))
473
474         query = ' AND '.join(reversed(stack))
475         joins = ' AND '.join(map(lambda j: j[0], self.__joins))
476         if joins:
477             query = '(%s) AND (%s)' % (joins, query)
478         return (query, flatten(params))
479
480     def get_tables(self):
481         return ['"%s"' % t._table for t in self.__all_tables]
482
483 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
484