4da2a70528af8599fceafd4a9fa8aa89b6075f5b
[odoo/odoo.git] / bin / osv / expression.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 ##############################################################################
4 #
5 #    OpenERP, Open Source Management Solution
6 #    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
7 #
8 #    This program is free software: you can redistribute it and/or modify
9 #    it under the terms of the GNU Affero General Public License as
10 #    published by the Free Software Foundation, either version 3 of the
11 #    License, or (at your option) any later version.
12 #
13 #    This program is distributed in the hope that it will be useful,
14 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
15 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 #    GNU Affero General Public License for more details.
17 #
18 #    You should have received a copy of the GNU Affero General Public License
19 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 #
21 ##############################################################################
22
23 from tools import flatten, reverse_enumerate
24 import fields
25
26
27 class expression(object):
28     """
29     parse a domain expression
30     use a real polish notation
31     leafs are still in a ('foo', '=', 'bar') format
32     For more info: http://christophe-simonis-at-tiny.blogspot.com/2008/08/new-new-domain-notation.html 
33     """
34
35     def _is_operator(self, element):
36         return isinstance(element, (str, unicode)) and element in ['&', '|', '!']
37
38     def _is_leaf(self, element, internal=False):
39         OPS = ('=', '!=', '<>', '<=', '<', '>', '>=', '=?', '=like', '=ilike', 'like', 'not like', 'ilike', 'not ilike', 'in', 'not in', 'child_of')
40         INTERNAL_OPS = OPS + ('inselect',)
41         return (isinstance(element, tuple) or isinstance(element, list)) \
42            and len(element) == 3 \
43            and (((not internal) and element[1] in OPS) \
44                 or (internal and element[1] in INTERNAL_OPS))
45
46     def __execute_recursive_in(self, cr, s, f, w, ids, op, type):
47         # todo: merge into parent query as sub-query
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.__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             working_table = table
117             main_table = table
118             fargs = left.split('.', 1)
119             if fargs[0] in table._inherit_fields:
120                 while True:
121                     field = main_table._columns.get(fargs[0], False)
122                     if field:
123                         working_table = main_table
124                         self.__field_tables[i] = working_table
125                         break
126                     working_table = main_table.pool.get(main_table._inherit_fields[fargs[0]][0])
127                     if working_table not in self.__all_tables:
128                         self.__joins.append('%s.%s=%s.%s' % (working_table._table, 'id', main_table._table, main_table._inherits[working_table._name]))
129                         self.__all_tables.add(working_table)
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                 continue
150
151             if field._properties and ((not field.store) or field._fnct_search):
152                 # this is a function field
153                 if not field._fnct_search:
154                     # the function field doesn't provide a search function and doesn't store
155                     # values in the database, so we must ignore it : we generate a dummy leaf
156                     self.__exp[i] = self.__DUMMY_LEAF
157                 else:
158                     subexp = field.search(cr, uid, table, left, [self.__exp[i]], context=context)
159                     # we assume that the expression is valid
160                     # we create a dummy leaf for forcing the parsing of the resulting expression
161                     self.__exp[i] = '&'
162                     self.__exp.insert(i + 1, self.__DUMMY_LEAF)
163                     for j, se in enumerate(subexp):
164                         self.__exp.insert(i + 2 + j, se)
165             # else, the value of the field is store in the database, so we search on it
166
167             elif field._type == 'one2many':
168                 # Applying recursivity on field(one2many)
169                 if operator == 'child_of':
170                     if isinstance(right, basestring):
171                         ids2 = [x[0] for x in field_obj.name_search(cr, uid, right, [], 'like', context=context, limit=None)]
172                     else:
173                         ids2 = list(right)
174                     if field._obj != working_table._name:
175                         dom = _rec_get(ids2, field_obj, left=left, prefix=field._obj)
176                     else:
177                         dom = _rec_get(ids2, working_table, parent=left)
178                     self.__exp = self.__exp[:i] + dom + self.__exp[i+1:]
179                 
180                 else:    
181                     call_null = True
182                     
183                     if right:
184                         if isinstance(right, basestring):
185                             ids2 = [x[0] for x in field_obj.name_search(cr, uid, right, [], operator, context=context, limit=None)]
186                             if ids2:
187                                 operator = 'in' 
188                         else:
189                             if not isinstance(right,list):
190                                 ids2 = [right]
191                             else:
192                                 ids2 = right    
193                         if not ids2:
194                             if operator in ['like','ilike','in','=']:
195                                 #no result found with given search criteria
196                                 call_null = False
197                                 self.__exp[i] = ('id','=',0)
198                             else:
199                                 call_null = True
200                                 operator = 'in' # operator changed because ids are directly related to main object
201                         else:
202                             call_null = False
203                             o2m_op = 'in'
204                             if operator in  ['not like','not ilike','not in','<>','!=']:
205                                 o2m_op = 'not in'
206                             self.__exp[i] = ('id', o2m_op, self.__execute_recursive_in(cr, field._fields_id, field_obj._table, 'id', ids2, operator, field._type))
207                     
208                     if call_null:
209                         o2m_op = 'not in'
210                         if operator in  ['not like','not ilike','not in','<>','!=']:
211                             o2m_op = 'in'                         
212                         self.__exp[i] = ('id', o2m_op, self.__execute_recursive_in(cr, field._fields_id, field_obj._table, 'id', [], operator, field._type) or [0])      
213
214             elif field._type == 'many2many':
215                 #FIXME
216                 if operator == 'child_of':
217                     if isinstance(right, basestring):
218                         ids2 = [x[0] for x in field_obj.name_search(cr, uid, right, [], 'like', context=context, limit=None)]
219                     else:
220                         ids2 = list(right)
221
222                     def _rec_convert(ids):
223                         if field_obj == table:
224                             return ids
225                         return self.__execute_recursive_in(cr, field._id1, field._rel, field._id2, ids, operator, field._type)
226
227                     dom = _rec_get(ids2, field_obj)
228                     ids2 = field_obj.search(cr, uid, dom, context=context)
229                     self.__exp[i] = ('id', 'in', _rec_convert(ids2))
230                 else:
231                     call_null_m2m = True
232                     if right:
233                         if isinstance(right, basestring):
234                             res_ids = [x[0] for x in field_obj.name_search(cr, uid, right, [], operator, context=context)]
235                             if res_ids:
236                                 opeartor = 'in'
237                         else:
238                             if not isinstance(right, list):
239                                 res_ids = [right]
240                             else:
241                                 res_ids = right
242                         if not res_ids:
243                             if operator in ['like','ilike','in','=']:
244                                 #no result found with given search criteria
245                                 call_null_m2m = False
246                                 self.__exp[i] = ('id','=',0)
247                             else: 
248                                 call_null_m2m = True
249                                 operator = 'in' # operator changed because ids are directly related to main object
250                         else:
251                             call_null_m2m = False
252                             m2m_op = 'in'        
253                             if operator in  ['not like','not ilike','not in','<>','!=']:
254                                 m2m_op = 'not in'
255                             
256                             self.__exp[i] = ('id', m2m_op, self.__execute_recursive_in(cr, field._id1, field._rel, field._id2, res_ids, operator, field._type) or [0])
257                     if call_null_m2m:
258                         m2m_op = 'not in'
259                         if operator in  ['not like','not ilike','not in','<>','!=']:
260                             m2m_op = 'in'                         
261                         self.__exp[i] = ('id', m2m_op, self.__execute_recursive_in(cr, field._id1, field._rel, field._id2, [], operator,  field._type) or [0])
262
263             elif field._type == 'many2one':
264                 if operator == 'child_of':
265                     if isinstance(right, basestring):
266                         ids2 = [x[0] for x in field_obj.name_search(cr, uid, right, [], 'like', limit=None)]
267                     elif isinstance(right, (int, long)):
268                         ids2 = list([right])
269                     else:
270                         ids2 = list(right)
271
272                     self.__operator = 'in'
273                     if field._obj != working_table._name:
274                         dom = _rec_get(ids2, field_obj, left=left, prefix=field._obj)
275                     else:
276                         dom = _rec_get(ids2, working_table, parent=left)
277                     self.__exp = self.__exp[:i] + dom + self.__exp[i+1:]
278                 else:
279                     if isinstance(right, basestring): # and not isinstance(field, fields.related):
280                         c = context.copy()
281                         c['active_test'] = False
282                         res_ids = field_obj.name_search(cr, uid, right, [], operator, limit=None, context=c)
283                         if not res_ids:
284                             self.__exp[i] = ('id','=',0)
285                         else:
286                             right = map(lambda x: x[0], res_ids)
287                             self.__exp[i] = (left, 'in', right)
288             else:
289                 # other field type
290                 # add the time part to datetime field when it's not there:
291                 if field._type == 'datetime' and self.__exp[i][2] and len(self.__exp[i][2]) == 10:
292                     
293                     self.__exp[i] = list(self.__exp[i])
294                     
295                     if operator in ('>', '>='):
296                         self.__exp[i][2] += ' 00:00:00'
297                     elif operator in ('<', '<='):
298                         self.__exp[i][2] += ' 23:59:59'
299                     
300                     self.__exp[i] = tuple(self.__exp[i])
301                         
302                 if field.translate:
303                     if operator in ('like', 'ilike', 'not like', 'not ilike'):
304                         right = '%%%s%%' % right
305
306                     operator = operator == '=like' and 'like' or operator
307
308                     query1 = '( SELECT res_id'          \
309                              '    FROM ir_translation'  \
310                              '   WHERE name = %s'       \
311                              '     AND lang = %s'       \
312                              '     AND type = %s'
313                     instr = ' %s'
314                     #Covering in,not in operators with operands (%s,%s) ,etc.
315                     if operator in ['in','not in']:
316                         instr = ','.join(['%s'] * len(right))
317                         query1 += '     AND value ' + operator +  ' ' +" (" + instr + ")"   \
318                              ') UNION ('                \
319                              '  SELECT id'              \
320                              '    FROM "' + working_table._table + '"'       \
321                              '   WHERE "' + left + '" ' + operator + ' ' +" (" + instr + "))"
322                     else:
323                         query1 += '     AND value ' + operator + instr +   \
324                              ') UNION ('                \
325                              '  SELECT id'              \
326                              '    FROM "' + working_table._table + '"'       \
327                              '   WHERE "' + left + '" ' + operator + instr + ")"
328
329                     query2 = [working_table._name + ',' + left,
330                               context.get('lang', False) or 'en_US',
331                               'model',
332                               right,
333                               right,
334                              ]
335
336                     self.__exp[i] = ('id', 'inselect', (query1, query2))
337
338         return self
339
340     def __leaf_to_sql(self, leaf, table):
341         if leaf == self.__DUMMY_LEAF:
342             return ('(1=1)', [])
343         left, operator, right = leaf
344         
345         if operator == 'inselect':
346             query = '(%s.%s in (%s))' % (table._table, left, right[0])
347             params = right[1]
348         elif operator in ['in', 'not in']:
349             params = right and right[:] or []
350             len_before = len(params)
351             for i in range(len_before)[::-1]:
352                 if params[i] == False:
353                     del params[i]
354
355             len_after = len(params)
356             check_nulls = len_after != len_before
357             query = '(1=0)'
358             
359             if len_after:
360                 if left == 'id':
361                     instr = ','.join(['%s'] * len_after)
362                 else:
363                     instr = ','.join([table._columns[left]._symbol_set[0]] * len_after)
364                 query = '(%s.%s %s (%s))' % (table._table, left, operator, instr)
365             else:
366                 # the case for [field, 'in', []] or [left, 'not in', []]
367                 if operator == 'in':
368                     query = '(%s.%s IS NULL)' % (table._table, left)
369                 else:
370                     query = '(%s.%s IS NOT NULL)' % (table._table, left)
371             if check_nulls:
372                 query = '(%s OR %s.%s IS NULL)' % (query, table._table, left)
373         else:
374             params = []
375             
376             if right == False and (leaf[0] in table._columns)  and table._columns[leaf[0]]._type=="boolean"  and (operator == '='):
377                 query = '(%s.%s IS NULL or %s.%s = false )' % (table._table, left,table._table, left)
378             elif (((right == False) and (type(right)==bool)) or (right is None)) and (operator == '='):
379                 query = '%s.%s IS NULL ' % (table._table, left)
380             elif right == False and (leaf[0] in table._columns)  and table._columns[leaf[0]]._type=="boolean"  and (operator in ['<>', '!=']):
381                 query = '(%s.%s IS NOT NULL and %s.%s != false)' % (table._table, left,table._table, left)
382             elif (((right == False) and (type(right)==bool)) or right is None) and (operator in ['<>', '!=']):
383                 query = '%s.%s IS NOT NULL' % (table._table, left)
384             elif (operator == '=?'):
385                 op = '='
386                 if (right is False or right is None):
387                     return ( 'TRUE',[])
388                 if left in table._columns:
389                         format = table._columns[left]._symbol_set[0]
390                         query = '(%s.%s %s %s)' % (table._table, left, op, format)
391                         params = table._columns[left]._symbol_set[1](right)
392                 else:
393                         query = "(%s.%s %s '%%s')" % (table._table, left, op)
394                         params = right
395
396             else:
397                 if left == 'id':
398                     query = '%s.id %s %%s' % (table._table, operator)
399                     params = right
400                 else:
401                     like = operator in ('like', 'ilike', 'not like', 'not ilike')
402
403                     op = {'=like':'like','=ilike':'ilike'}.get(operator,operator)
404                     if left in table._columns:
405                         format = like and '%s' or table._columns[left]._symbol_set[0]
406                         query = '(%s.%s %s %s)' % (table._table, left, op, format)
407                     else:
408                         query = "(%s.%s %s '%s')" % (table._table, left, op, right)
409
410                     add_null = False
411                     if like:
412                         if isinstance(right, str):
413                             str_utf8 = right
414                         elif isinstance(right, unicode):
415                             str_utf8 = right.encode('utf-8')
416                         else:
417                             str_utf8 = str(right)
418                         params = '%%%s%%' % str_utf8
419                         add_null = not str_utf8
420                     elif left in table._columns:
421                         params = table._columns[left]._symbol_set[1](right)
422
423                     if add_null:
424                         query = '(%s OR %s IS NULL)' % (query, left)
425
426         if isinstance(params, basestring):
427             params = [params]
428         return (query, params)
429
430
431     def to_sql(self):
432         stack = []
433         params = []
434         for i, e in reverse_enumerate(self.__exp):
435             if self._is_leaf(e, internal=True):
436                 table = self.__field_tables.get(i, self.__main_table)
437                 q, p = self.__leaf_to_sql(e, table)
438                 params.insert(0, p)
439                 stack.append(q)
440             else:
441                 if e == '!':
442                     stack.append('(NOT (%s))' % (stack.pop(),))
443                 else:
444                     ops = {'&': ' AND ', '|': ' OR '}
445                     q1 = stack.pop()
446                     q2 = stack.pop()
447                     stack.append('(%s %s %s)' % (q1, ops[e], q2,))
448
449         query = ' AND '.join(reversed(stack))
450         joins = ' AND '.join(self.__joins)
451         if joins:
452             query = '(%s) AND (%s)' % (joins, query)
453         return (query, flatten(params))
454
455     def get_tables(self):
456         return ['"%s"' % t._table for t in self.__all_tables]
457
458 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
459