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