domains: allow None to be passed as right operand of a leaf (produce a IS NULL sql...
[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(ids, 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, limit=None)]
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', limit=None)]
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.name_search(cr, uid, right, [], 'like', limit=None)]
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, limit=None)
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         if leaf == self.__DUMMY_LEAF:
207             return ('(1=1)', [])
208         left, operator, right = leaf
209
210         if operator == 'inselect':
211             query = '(%s.%s in (%s))' % (table._table, left, right[0])
212             params = right[1]
213         elif operator in ['in', 'not in']:
214             params = right[:]
215             len_before = len(params)
216             for i in range(len_before)[::-1]:
217                 if params[i] == False:
218                     del params[i]
219
220             len_after = len(params)
221             check_nulls = len_after != len_before
222             query = '(1=0)'
223
224             if len_after:
225                 if left == 'id':
226                      instr = ','.join(['%d'] * len_after)
227                 else:
228                     instr = ','.join([table._columns[left]._symbol_set[0]] * len_after)
229                 query = '(%s.%s %s (%s))' % (table._table, left, operator, instr)
230
231             if check_nulls:
232                 query = '(%s OR %s IS NULL)' % (query, left)
233         else:
234             params = []
235             if (right == False or right is None) and operator == '=':
236                 query = '%s IS NULL' % left
237             elif (right == False or right is None) and operator in ['<>', '!=']:
238                 query = '%s IS NOT NULL' % left
239             else:
240                 if left == 'id':
241                     query = '%s.id %s %%s' % (table._table, operator)
242                     params = right
243                 else:
244                     like = operator in ('like', 'ilike', 'not like', 'not ilike')
245
246                     op = operator == '=like' and 'like' or operator
247                     if left in table._columns:
248                         format = like and '%s' or table._columns[left]._symbol_set[0]
249                         query = '(%s.%s %s %s)' % (table._table, left, op, format)
250                     else:
251                         query = "(%s.%s %s '%s')" % (table._table, left, op, right)
252
253                     add_null = False
254                     if like:
255                         if isinstance(right, str):
256                             str_utf8 = right
257                         elif isinstance(right, unicode):
258                             str_utf8 = right.encode('utf-8')
259                         else:
260                             str_utf8 = str(right)
261                         params = '%%%s%%' % str_utf8
262                         add_null = not str_utf8
263                     elif left in table._columns:
264                         params = table._columns[left]._symbol_set[1](right)
265
266                     if add_null:
267                         query = '(%s OR %s IS NULL)' % (query, left)
268
269         if isinstance(params, basestring):
270             params = [params]
271         return (query, params)
272
273
274     def to_sql(self):
275         stack = []
276         params = []
277         for i, e in reverse_enumerate(self.__exp):
278             if self._is_leaf(e, internal=True):
279                 table = self.__tables.get(i, self.__main_table)
280                 q, p = self.__leaf_to_sql(e, table)
281                 params.insert(0, p)
282                 stack.append(q)
283             else:
284                 if e == '!':
285                     stack.append('(NOT (%s))' % (stack.pop(),))
286                 else:
287                     ops = {'&': ' AND ', '|': ' OR '}
288                     q1 = stack.pop()
289                     q2 = stack.pop()
290                     stack.append('(%s %s %s)' % (q1, ops[e], q2,))
291
292         query = ' AND '.join(reversed(stack))
293         joins = ' AND '.join(map(lambda j: j[0], self.__joins))
294         if joins:
295             query = '(%s) AND (%s)' % (joins, query)
296         return (query, flatten(params))
297
298     def get_tables(self):
299         return ['"%s"' % t._table for t in set(self.__tables.values()+[self.__main_table])]
300
301 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
302