2 # -*- coding: utf-8 -*-
3 ##############################################################################
5 # OpenERP, Open Source Management Solution
6 # Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
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.
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.
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/>.
21 ##############################################################################
23 from tools import flatten, reverse_enumerate
27 class expression(object):
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
35 def _is_operator(self, element):
36 return isinstance(element, (str, unicode)) and element in ['&', '|', '!']
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))
46 def __execute_recursive_in(self, cr, s, f, w, ids, op, type):
47 # todo: merge into parent query as sub-query
50 if op in ['<','>','>=','<=']:
51 cr.execute('SELECT "%s"' \
53 ' WHERE "%s" %s %%s' % (s, f, w, op), (ids[0],))
54 res.extend([r[0] for r in cr.fetchall()])
56 for i in range(0, len(ids), cr.IN_MAX):
57 subids = ids[i:i+cr.IN_MAX]
58 cr.execute('SELECT "%s"' \
60 ' WHERE "%s" IN %%s' % (s, f, w),(tuple(subids),))
61 res.extend([r[0] for r in cr.fetchall()])
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()])
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,))
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()
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
83 def parse(self, cr, uid, table, context):
84 """ transform the leafs of the expression """
88 def _rec_get(ids, table, parent=None, left='id', prefix=''):
89 if table._parent_store and (not table.pool._init):
90 # TODO: Improve where joins are implemented for many with '.', replace by:
91 # doms += ['&',(prefix+'.parent_left','<',o.parent_right),(prefix+'.parent_left','>=',o.parent_left)]
93 for o in table.browse(cr, uid, ids, context=context):
96 doms += ['&', ('parent_left', '<', o.parent_right), ('parent_left', '>=', o.parent_left)]
98 return [(left, 'in', table.search(cr, uid, doms, context=context))]
101 def rg(ids, table, parent):
104 ids2 = table.search(cr, uid, [(parent, 'in', ids)], context=context)
105 return ids + rg(ids2, table, parent)
106 return [(left, 'in', rg(ids, table, parent or table._parent_name))]
108 self.__main_table = table
109 self.__all_tables.add(table)
112 while i + 1<len(self.__exp):
115 if self._is_operator(e) or e == self.__DUMMY_LEAF:
117 left, operator, right = e
118 operator = operator.lower()
119 working_table = table
121 fargs = left.split('.', 1)
122 if fargs[0] in table._inherit_fields:
124 field = main_table._columns.get(fargs[0], False)
126 working_table = main_table
127 self.__field_tables[i] = working_table
129 working_table = main_table.pool.get(main_table._inherit_fields[fargs[0]][0])
130 if working_table not in self.__all_tables:
131 self.__joins.append('%s.%s=%s.%s' % (working_table._table, 'id', main_table._table, main_table._inherits[working_table._name]))
132 self.__all_tables.add(working_table)
133 main_table = working_table
135 field = working_table._columns.get(fargs[0], False)
137 if left == 'id' and operator == 'child_of':
138 dom = _rec_get(right, working_table)
139 self.__exp = self.__exp[:i] + dom + self.__exp[i+1:]
142 field_obj = table.pool.get(field._obj)
144 if field._type == 'many2one':
145 right = field_obj.search(cr, uid, [(fargs[1], operator, right)], context=context)
146 self.__exp[i] = (fargs[0], 'in', right)
147 # Making search easier when there is a left operand as field.o2m or field.m2m
148 if field._type in ['many2many','one2many']:
149 right = field_obj.search(cr, uid, [(fargs[1], operator, right)], context=context)
150 right1 = table.search(cr, uid, [(fargs[0],'in', right)], context=context)
151 self.__exp[i] = ('id', 'in', right1)
154 if field._properties and ((not field.store) or field._fnct_search):
155 # this is a function field
156 if not field._fnct_search:
157 # the function field doesn't provide a search function and doesn't store
158 # values in the database, so we must ignore it : we generate a dummy leaf
159 self.__exp[i] = self.__DUMMY_LEAF
161 subexp = field.search(cr, uid, table, left, [self.__exp[i]], context=context)
162 # we assume that the expression is valid
163 # we create a dummy leaf for forcing the parsing of the resulting expression
165 self.__exp.insert(i + 1, self.__DUMMY_LEAF)
166 for j, se in enumerate(subexp):
167 self.__exp.insert(i + 2 + j, se)
168 # else, the value of the field is store in the database, so we search on it
170 elif field._type == 'one2many':
171 # Applying recursivity on field(one2many)
172 if operator == 'child_of':
173 if isinstance(right, basestring):
174 ids2 = [x[0] for x in field_obj.name_search(cr, uid, right, [], 'like', context=context, limit=None)]
177 if field._obj != working_table._name:
178 dom = _rec_get(ids2, field_obj, left=left, prefix=field._obj)
180 dom = _rec_get(ids2, working_table, parent=left)
181 self.__exp = self.__exp[:i] + dom + self.__exp[i+1:]
187 if isinstance(right, basestring):
188 ids2 = [x[0] for x in field_obj.name_search(cr, uid, right, [], operator, context=context, limit=None)]
192 if not isinstance(right,list):
197 if operator in ['like','ilike','in','=']:
198 #no result found with given search criteria
200 self.__exp[i] = ('id','=',0)
203 operator = 'in' # operator changed because ids are directly related to main object
207 if operator in ['not like','not ilike','not in','<>','!=']:
209 self.__exp[i] = ('id', o2m_op, self.__execute_recursive_in(cr, field._fields_id, field_obj._table, 'id', ids2, operator, field._type))
213 if operator in ['not like','not ilike','not in','<>','!=']:
215 self.__exp[i] = ('id', o2m_op, self.__execute_recursive_in(cr, field._fields_id, field_obj._table, 'id', [], operator, field._type) or [0])
217 elif field._type == 'many2many':
219 if operator == 'child_of':
220 if isinstance(right, basestring):
221 ids2 = [x[0] for x in field_obj.name_search(cr, uid, right, [], 'like', context=context, limit=None)]
225 def _rec_convert(ids):
226 if field_obj == table:
228 return self.__execute_recursive_in(cr, field._id1, field._rel, field._id2, ids, operator, field._type)
230 dom = _rec_get(ids2, field_obj)
231 ids2 = field_obj.search(cr, uid, dom, context=context)
232 self.__exp[i] = ('id', 'in', _rec_convert(ids2))
236 if isinstance(right, basestring):
237 res_ids = [x[0] for x in field_obj.name_search(cr, uid, right, [], operator, context=context)]
241 if not isinstance(right, list):
246 if operator in ['like','ilike','in','=']:
247 #no result found with given search criteria
248 call_null_m2m = False
249 self.__exp[i] = ('id','=',0)
252 operator = 'in' # operator changed because ids are directly related to main object
254 call_null_m2m = False
256 if operator in ['not like','not ilike','not in','<>','!=']:
259 self.__exp[i] = ('id', m2m_op, self.__execute_recursive_in(cr, field._id1, field._rel, field._id2, res_ids, operator, field._type) or [0])
262 if operator in ['not like','not ilike','not in','<>','!=']:
264 self.__exp[i] = ('id', m2m_op, self.__execute_recursive_in(cr, field._id1, field._rel, field._id2, [], operator, field._type) or [0])
266 elif field._type == 'many2one':
267 if operator == 'child_of':
268 if isinstance(right, basestring):
269 ids2 = [x[0] for x in field_obj.name_search(cr, uid, right, [], 'like', limit=None)]
270 elif isinstance(right, (int, long)):
275 self.__operator = 'in'
276 if field._obj != working_table._name:
277 dom = _rec_get(ids2, field_obj, left=left, prefix=field._obj)
279 dom = _rec_get(ids2, working_table, parent=left)
280 self.__exp = self.__exp[:i] + dom + self.__exp[i+1:]
282 def _get_expression(field_obj,cr, uid, left, right, operator, context=None):
286 c['active_test'] = False
287 dict_op = {'not in':'!=','in':'='}
288 if isinstance(right,tuple):
290 if (not isinstance(right,list)) and operator in ['not in','in']:
291 operator = dict_op[operator]
293 res_ids = field_obj.name_search(cr, uid, right, [], operator, limit=None, context=c)
297 right = map(lambda x: x[0], res_ids)
298 return (left, 'in', right)
301 if isinstance(right, basestring): # and not isinstance(field, fields.related):
303 elif isinstance(right, list) or isinstance(right, tuple):
306 if not isinstance(ele, basestring):
311 self.__exp[i] = _get_expression(field_obj,cr, uid, left, right, operator, context=context)
314 # add the time part to datetime field when it's not there:
315 if field._type == 'datetime' and self.__exp[i][2] and len(self.__exp[i][2]) == 10:
317 self.__exp[i] = list(self.__exp[i])
319 if operator in ('>', '>='):
320 self.__exp[i][2] += ' 00:00:00'
321 elif operator in ('<', '<='):
322 self.__exp[i][2] += ' 23:59:59'
324 self.__exp[i] = tuple(self.__exp[i])
327 if operator in ('like', 'ilike', 'not like', 'not ilike'):
328 right = '%%%s%%' % right
330 operator = operator == '=like' and 'like' or operator
332 query1 = '( SELECT res_id' \
333 ' FROM ir_translation' \
338 #Covering in,not in operators with operands (%s,%s) ,etc.
339 if operator in ['in','not in']:
340 instr = ','.join(['%s'] * len(right))
341 query1 += ' AND value ' + operator + ' ' +" (" + instr + ")" \
344 ' FROM "' + working_table._table + '"' \
345 ' WHERE "' + left + '" ' + operator + ' ' +" (" + instr + "))"
347 query1 += ' AND value ' + operator + instr + \
350 ' FROM "' + working_table._table + '"' \
351 ' WHERE "' + left + '" ' + operator + instr + ")"
353 query2 = [working_table._name + ',' + left,
354 context.get('lang', False) or 'en_US',
360 self.__exp[i] = ('id', 'inselect', (query1, query2))
364 def __leaf_to_sql(self, leaf, table):
365 if leaf == self.__DUMMY_LEAF:
367 left, operator, right = leaf
369 if operator == 'inselect':
370 query = '(%s.%s in (%s))' % (table._table, left, right[0])
372 elif operator in ['in', 'not in']:
373 params = right and right[:] or []
374 len_before = len(params)
375 for i in range(len_before)[::-1]:
376 if params[i] == False:
379 len_after = len(params)
380 check_nulls = len_after != len_before
385 instr = ','.join(['%s'] * len_after)
387 instr = ','.join([table._columns[left]._symbol_set[0]] * len_after)
388 query = '(%s.%s %s (%s))' % (table._table, left, operator, instr)
390 # the case for [field, 'in', []] or [left, 'not in', []]
392 query = '(%s.%s IS NULL)' % (table._table, left)
394 query = '(%s.%s IS NOT NULL)' % (table._table, left)
396 query = '(%s OR %s.%s IS NULL)' % (query, table._table, left)
400 if right == False and (leaf[0] in table._columns) and table._columns[leaf[0]]._type=="boolean" and (operator == '='):
401 query = '(%s.%s IS NULL or %s.%s = false )' % (table._table, left,table._table, left)
402 elif (((right == False) and (type(right)==bool)) or (right is None)) and (operator == '='):
403 query = '%s.%s IS NULL ' % (table._table, left)
404 elif right == False and (leaf[0] in table._columns) and table._columns[leaf[0]]._type=="boolean" and (operator in ['<>', '!=']):
405 query = '(%s.%s IS NOT NULL and %s.%s != false)' % (table._table, left,table._table, left)
406 elif (((right == False) and (type(right)==bool)) or right is None) and (operator in ['<>', '!=']):
407 query = '%s.%s IS NOT NULL' % (table._table, left)
408 elif (operator == '=?'):
410 if (right is False or right is None):
412 if left in table._columns:
413 format = table._columns[left]._symbol_set[0]
414 query = '(%s.%s %s %s)' % (table._table, left, op, format)
415 params = table._columns[left]._symbol_set[1](right)
417 query = "(%s.%s %s '%%s')" % (table._table, left, op)
422 query = '%s.id %s %%s' % (table._table, operator)
425 like = operator in ('like', 'ilike', 'not like', 'not ilike')
427 op = {'=like':'like','=ilike':'ilike'}.get(operator,operator)
428 if left in table._columns:
429 format = like and '%s' or table._columns[left]._symbol_set[0]
430 query = '(%s.%s %s %s)' % (table._table, left, op, format)
432 query = "(%s.%s %s '%s')" % (table._table, left, op, right)
436 if isinstance(right, str):
438 elif isinstance(right, unicode):
439 str_utf8 = right.encode('utf-8')
441 str_utf8 = str(right)
442 params = '%%%s%%' % str_utf8
443 add_null = not str_utf8
444 elif left in table._columns:
445 params = table._columns[left]._symbol_set[1](right)
448 query = '(%s OR %s IS NULL)' % (query, left)
450 if isinstance(params, basestring):
452 return (query, params)
458 for i, e in reverse_enumerate(self.__exp):
459 if self._is_leaf(e, internal=True):
460 table = self.__field_tables.get(i, self.__main_table)
461 q, p = self.__leaf_to_sql(e, table)
466 stack.append('(NOT (%s))' % (stack.pop(),))
468 ops = {'&': ' AND ', '|': ' OR '}
471 stack.append('(%s %s %s)' % (q1, ops[e], q2,))
473 query = ' AND '.join(reversed(stack))
474 joins = ' AND '.join(self.__joins)
476 query = '(%s) AND (%s)' % (joins, query)
477 return (query, flatten(params))
479 def get_tables(self):
480 return ['"%s"' % t._table for t in self.__all_tables]
482 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: