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(ids2, 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)]
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')]
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.search_name(cr, uid, right, [], 'like')]
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)
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 left, operator, right = leaf
208 if operator == 'inselect':
209 query = '(%s.%s in (%s))' % (table._table, left, right[0])
211 elif operator in ['in', 'not in']:
213 len_before = len(params)
214 for i in range(len_before)[::-1]:
215 if params[i] == False:
218 len_after = len(params)
219 check_nulls = len_after != len_before
224 instr = ','.join(['%d'] * len_after)
226 instr = ','.join([table._columns[left]._symbol_set[0]] * len_after)
227 query = '(%s.%s %s (%s))' % (table._table, left, operator, instr)
230 query = '(%s OR %s IS NULL)' % (query, left)
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
239 query = '%s.id %s %%s' % (table._table, operator)
242 like = operator in ('like', 'ilike', 'not like', 'not ilike')
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)
249 query = "(%s.%s %s '%s')" % (table._table, left, op, right)
253 if isinstance(right, str):
255 elif isinstance(right, unicode):
256 str_utf8 = right.encode('utf-8')
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)
265 query = '(%s OR %s IS NULL)' % (query, left)
267 if isinstance(params, basestring):
269 return (query, 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)
283 stack.append('(NOT (%s))' % (stack.pop(),))
285 ops = {'&': ' AND ', '|': ' OR '}
288 stack.append('(%s %s %s)' % (q1, ops[e], q2,))
290 query = ' AND '.join(reversed(stack))
291 joins = ' AND '.join(map(lambda j: j[0], self.__joins))
293 query = '(%s) AND (%s)' % (joins, query)
294 return (query, flatten(params))
296 def get_tables(self):
297 return ['"%s"' % t._table for t in set(self.__tables.values()+[self.__main_table])]
299 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: