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