bugfix: change variable usage
[odoo/odoo.git] / bin / osv / expression.py
1 #!/usr/bin/env python
2 # -*- encoding: utf-8 -*-
3
4 from tools import flatten, reverse_enumerate
5
6
7 class expression(object):
8     """
9     parse a domain expression
10     use a real polish notation
11     leafs are still in a ('foo', '=', 'bar') format
12     For more info: http://...
13     """
14
15     def _is_operator(self, element):
16         return isinstance(element, str) \
17            and element in ['&', '|', '!']
18
19     def _is_leaf(self, element):
20         return isinstance(element, tuple) \
21            and len(element) == 3 \
22            and element[1] in ('=', '!=', '<>', '<=', '<', '>', '>=', '=like', 'like', 'not like', 'ilike', 'not ilike', 'in', 'not in', 'child_of')
23
24     def __execute_recursive_in(self, cr, s, f, w, ids):
25         #deprecated -> use _left and _right...
26         res = []
27         for i in range(0, len(ids), cr.IN_MAX):
28             subids = ids[i:i+cr.IN_MAX]
29             cr.execute('SELECT "%s"'    \
30                        '  FROM "%s"'    \
31                        ' WHERE "%s" in (%s)' % (s, f, w, ','.join(['%d']*len(subids))),
32                        subids)
33             res.extend([r[0] for r in cr.fetchall()])
34         return res
35
36
37     def __init__(self, exp):
38
39         # check if the expression is valid
40         if not reduce(lambda acc, val: acc and (self._is_operator(val) or self._is_leaf(val)), exp, True):
41             raise ValueError('Bad expression: %r' % (exp,))
42
43         self.__exp = exp
44         self.__tables = {}  # used to store the table to use for the sql generation. key = index of the leaf
45         self.__joins = []
46         self.__main_table = None # 'root' table. set by parse()
47
48         self.__DUMMY_LEAF = (1, '=', 1) # a dummy leaf that must not be parsed or sql generated
49
50
51     def parse(self, cr, uid, table, context):
52         """ transform the leafs of the expression """
53
54         def _rec_get(ids, table, parent):
55             if not ids:
56                 return []
57             ids2 = table.search(cr, uid, [(parent, 'in', ids)], context=context)
58             return ids + _rec_get(ids2, table, parent)
59
60         if not self.__exp:
61             return self
62
63         self.__main_table = table
64         working_table = table
65         
66         for i, e in enumerate(self.__exp):
67             if self._is_operator(e) or e == self.__DUMMY_LEAF:
68                 continue
69             left, operator, right = e
70
71             if left in table._inherit_fields:
72                 working_table = table.pool.get(table._inherit_fields[left][0])
73                 if working_table not in self.__tables.values():
74                     self.__joins.append('%s.%s' % (table._table, table._inherits[working_table._name]))
75             
76             self.__tables[i] = working_table
77             
78             fargs = left.split('.', 1)
79             field = working_table._columns.get(fargs[0], False)
80             if not field:
81                 if left == 'id' and operator == 'child_of':
82                     right += _rec_get(right, working_table, working_table._parent_name)
83                     self.__exp[i] = ('id', 'in', right)
84                 continue
85             
86             field_obj = table.pool.get(field._obj)
87             if len(fargs) > 1:
88                 if field._type == 'many2one':
89                     right = field_obj.search(cr, uid, [(fargs[1], operator, right)], context=context)
90                     self.__exp[i] = (fargs[0], 'in', right)
91                 continue
92
93             if field._properties:
94                 # this is a function field
95                 if not field.store:
96                     if not field._fnct_search:
97                         # the function field doesn't provide a search function and doesn't store
98                         # values in the database, so we must ignore it : we generate a dummy leaf
99                         self.__exp[i] = self.__DUMMY_LEAF
100                     else:
101                         subexp = field.search(cr, uid, table, left, [self.__exp[i]])
102                         # we assume that the expression is valid 
103                         # we create a dummy leaf for forcing the parsing of the resulting expression
104                         self.__exp[i] = '&'
105                         self.__exp.insert(i + 1, self.__DUMMY_LEAF)
106                         for j, se in enumerate(subexp):
107                             self.__exp.insert(i + 2 + j, se)
108                 
109                 # else, the value of the field is store in the database, so we search on it
110
111
112             elif field._type == 'one2many':
113                 if isinstance(right, basestring):
114                     ids2 = [x[0] for x in field_obj.name_search(cr, uid, right, [], operator)]
115                 else:
116                     ids2 = list(right)
117                 if not ids2:
118                     self.__exp[i] = ('id', '=', '0')
119                 else:
120                     self.__exp[i] = ('id', 'in', self.__execute_recursive_in(cr, field._fields_id, field_obj._table, 'id', ids2))
121
122             elif field._type == 'many2many':
123                 #FIXME
124                 if operator == 'child_of':
125                     if isinstance(right, basestring):
126                         ids2 = [x[0] for x in field_obj.name_search(cr, uid, right, [], 'like')]
127                     else:
128                         ids2 = list(right)
129
130                     def _rec_convert(ids):
131                         if field_obj == table:
132                             return ids
133                         return self.__execute_recursive_in(cr, field._id1, field._rel, field._id2, ids)
134
135                     self.__exp[i] = ('id', 'in', _rec_convert(ids2 + _rec_get(ids2, field_obj, working_table._parent_name)))
136                 else:
137                     if isinstance(right, basestring):
138                         res_ids = [x[0] for x in field_obj.name_search(cr, uid, right, [], operator)]
139                     else:
140                         res_ids = list(right)
141                     self.__exp[i] = ('id', 'in', self.__execute_recursive_in(cr, field._id1, field._rel, field._id2, res_ids) or [0])
142             elif field._type == 'many2one':
143                 if operator == 'child_of':
144                     if isinstance(right, basestring):
145                         ids2 = [x[0] for x in field_obj.search_name(cr, uid, right, [], 'like')]
146                     else:
147                         ids2 = list(right)
148
149                     self.__operator = 'in'
150                     if field._obj != working_table._name:
151                         right = ids2 + _rec_get(ids2, field_obj, working_table._parent_name)
152                     else:
153                         right = ids2 + _rec_get(ids2, working_table, left)
154                         left = 'id'
155                     self.__exp[i] = (left, 'in', right)
156                 else:
157                     if isinstance(right, basestring):
158                         res_ids = field_obj.name_search(cr, uid, right, [], operator)
159                         right = map(lambda x: x[0], res_ids)
160                         self.__exp[i] = (left, 'in', right)
161             else:
162                 # other field type
163                 if field.translate:
164                     if operator in ('like', 'ilike', 'not like', 'not ilike'):
165                         right = '%%%s%%' % right
166
167                     query1 = '( SELECT res_id'          \
168                              '    FROM ir_translation'  \
169                              '   WHERE name = %s'       \
170                              '     AND lang = %s'       \
171                              '     AND type = %s'       \
172                              '     AND value ' + operator + ' %s'    \
173                              ') UNION ('                \
174                              '  SELECT id'              \
175                              '    FROM "' + working_table._table + '"'       \
176                              '   WHERE "' + left + '" ' + operator + ' %s' \
177                              ')'
178                     query2 = [working_table._name + ',' + left,
179                               context.get('lang', False) or 'en_US',
180                               'model',
181                               right,
182                               right,
183                              ]
184
185                     self.__exp[i] = ('id', 'inselect', (query1, query2))
186
187         return self
188
189     def __leaf_to_sql(self, leaf, table):
190         left, operator, right = leaf
191
192         if operator == 'inselect':
193             query = '(%s.%s in (%s))' % (table._table, left, right[0])
194             params = right[1]
195         elif operator in ['in', 'not in']:
196             params = right[:]
197             len_before = len(params)
198             for i in range(len_before)[::-1]:
199                 if params[i] == False:
200                     del params[i]
201
202             len_after = len(params)
203             check_nulls = len_after != len_before
204             query = '(1=0)'
205
206             if len_after:
207                 if left == 'id':
208                      instr = ','.join(['%d'] * len_after)
209                 else:
210                     instr = ','.join([table._columns[left]._symbol_set[0]] * len_after)
211                 query = '(%s.%s %s (%s))' % (table._table, left, operator, instr)
212
213             if check_nulls:
214                 query = '(%s OR %s IS NULL)' % (query, left)
215         else:
216             params = []
217             if right is False and operator == '=':
218                 query = '%s IS NULL' % left
219             elif right is False and operator in ['<>', '!=']:
220                 query = '%s IS NOT NULL' % left
221             else:
222                 if left == 'id':
223                     query = '%s.id %s %%s' % (table._table, operator)
224                     params = right
225                 else:
226                     like = operator in ('like', 'ilike', 'not like', 'not ilike')
227
228                     op = operator == '=like' and 'like' or operator
229                     if left in table._columns:
230                         format = like and '%s' or table._columns[left]._symbol_set[0]
231                         query = '(%s.%s %s %s)' % (table._table, left, op, format)
232                     else:
233                         query = "(%s.%s %s '%s')" % (table._table, left, op, right)
234
235                     add_null = False
236                     if like:
237                         if isinstance(right, str):
238                             str_utf8 = right
239                         elif isinstance(right, unicode):
240                             str_utf8 = right.encode('utf-8')
241                         else:
242                             str_utf8 = str(right)
243                         params = '%%%s%%' % str_utf8
244                         add_null = not str_utf8
245                     elif left in table._columns:
246                         params = table._columns[left]._symbol_set[1](right)
247
248                     if add_null:
249                         query = '(%s OR %s IS NULL)' % (query, left)
250
251         if isinstance(params, basestring):
252             params = [params]
253         return (query, params)
254
255
256     def to_sql(self):
257         stack = []
258         params = []
259         for i, e in reverse_enumerate(self.__exp):
260             if self._is_leaf(e):
261                 table = self.__tables.has_key(i) and self.__tables[i] or self.__main_table
262                 q, p = self.__leaf_to_sql(e, table)
263                 params.insert(0, p)
264                 stack.append(q)
265             else:
266                 if e == '!':
267                     stack.append('(NOT (%s))' % (stack.pop(),))
268                 else:
269                     ops = {'&': ' AND ', '|': ' OR '}
270                     q1 = stack.pop()
271                     q2 = stack.pop()
272                     stack.append('(%s %s %s)' % (q1, ops[e], q2,))
273         
274         query = ' AND '.join(reversed(stack))
275         joins = ' AND '.join(map(lambda j: '%s.id = %s' % (self.__main_table._table, j), self.__joins))
276         if joins:
277             query = '(%s AND (%s))' % (joins, query)
278         return (query, flatten(params))
279
280     def get_tables(self):
281         return ['"%s"' % t._table for t in set(self.__tables.values())]
282
283 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
284