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