2 # -*- encoding: utf-8 -*-
4 from tools import flatten, reverse_enumerate
7 class expression(object):
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
15 def _is_operator(self, element):
16 return isinstance(element, str) \
17 and element in ['&', '|', '!']
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))
27 def __execute_recursive_in(self, cr, s, f, w, ids):
29 for i in range(0, len(ids), cr.IN_MAX):
30 subids = ids[i:i+cr.IN_MAX]
31 cr.execute('SELECT "%s"' \
33 ' WHERE "%s" in (%s)' % (s, f, w, ','.join(['%d']*len(subids))),
35 res.extend([r[0] for r in cr.fetchall()])
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,))
44 self.__tables = {} # used to store the table to use for the sql generation. key = index of the leaf
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
50 def parse(self, cr, uid, table, context):
51 """ transform the leafs of the expression """
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)]
60 for o in table.browse(cr, uid, ids, context=context):
63 doms += ['&', ('parent_left', '<', o.parent_right), ('parent_left', '>=', o.parent_left)]
65 return [(left, 'in', table.search(cr, uid, doms, context=context))]
68 def rg(ids, table, parent):
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))]
75 self.__main_table = table
78 while i + 1<len(self.__exp):
81 if self._is_operator(e) or e == self.__DUMMY_LEAF:
83 left, operator, right = e
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))
91 self.__tables[i] = working_table
93 fargs = left.split('.', 1)
94 field = working_table._columns.get(fargs[0], False)
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:]
101 field_obj = table.pool.get(field._obj)
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)
108 if field._properties:
109 # this is a function field
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
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
120 self.__exp.insert(i + 1, self.__DUMMY_LEAF)
121 for j, se in enumerate(subexp):
122 self.__exp.insert(i + 2 + j, se)
124 # else, the value of the field is store in the database, so we search on it
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)]
133 self.__exp[i] = ('id', '=', '0')
135 self.__exp[i] = ('id', 'in', self.__execute_recursive_in(cr, field._fields_id, field_obj._table, 'id', ids2))
137 elif field._type == 'many2many':
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)]
145 def _rec_convert(ids):
146 if field_obj == table:
148 return self.__execute_recursive_in(cr, field._id1, field._rel, field._id2, ids)
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))
154 if isinstance(right, basestring):
155 res_ids = [x[0] for x in field_obj.name_search(cr, uid, right, [], operator)]
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)]
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)
170 dom = _rec_get(ids2, working_table, left)
171 self.__exp = self.__exp[:i] + dom + self.__exp[i+1:]
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)
180 if operator in ('like', 'ilike', 'not like', 'not ilike'):
181 right = '%%%s%%' % right
183 query1 = '( SELECT res_id' \
184 ' FROM ir_translation' \
188 ' AND value ' + operator + ' %s' \
191 ' FROM "' + working_table._table + '"' \
192 ' WHERE "' + left + '" ' + operator + ' %s' \
194 query2 = [working_table._name + ',' + left,
195 context.get('lang', False) or 'en_US',
201 self.__exp[i] = ('id', 'inselect', (query1, query2))
205 def __leaf_to_sql(self, leaf, table):
206 if leaf == self.__DUMMY_LEAF:
208 left, operator, right = leaf
210 if operator == 'inselect':
211 query = '(%s.%s in (%s))' % (table._table, left, right[0])
213 elif operator in ['in', 'not in']:
215 len_before = len(params)
216 for i in range(len_before)[::-1]:
217 if params[i] == False:
220 len_after = len(params)
221 check_nulls = len_after != len_before
226 instr = ','.join(['%d'] * len_after)
228 instr = ','.join([table._columns[left]._symbol_set[0]] * len_after)
229 query = '(%s.%s %s (%s))' % (table._table, left, operator, instr)
232 query = '(%s OR %s IS NULL)' % (query, left)
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
241 query = '%s.id %s %%s' % (table._table, operator)
244 like = operator in ('like', 'ilike', 'not like', 'not ilike')
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)
251 query = "(%s.%s %s '%s')" % (table._table, left, op, right)
255 if isinstance(right, str):
257 elif isinstance(right, unicode):
258 str_utf8 = right.encode('utf-8')
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)
267 query = '(%s OR %s IS NULL)' % (query, left)
269 if isinstance(params, basestring):
271 return (query, 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)
285 stack.append('(NOT (%s))' % (stack.pop(),))
287 ops = {'&': ' AND ', '|': ' OR '}
290 stack.append('(%s %s %s)' % (q1, ops[e], q2,))
292 query = ' AND '.join(reversed(stack))
293 joins = ' AND '.join(map(lambda j: j[0], self.__joins))
295 query = '(%s) AND (%s)' % (joins, query)
296 return (query, flatten(params))
298 def get_tables(self):
299 return ['"%s"' % t._table for t in set(self.__tables.values()+[self.__main_table])]
301 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: