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