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://...
15 def _is_operator(self, element):
16 return isinstance(element, str) \
17 and element in ['&', '|', '!']
19 def _is_leaf(self, element):
20 return isinstance(element, tuple) \
21 and len(element) == 3 \
22 and element[1] in ('=', '!=', '<>', '<=', '<', '>', '>=', '=like', 'like', 'not like', 'ilike', 'not ilike', 'in', 'not in', 'child_of')
24 def __execute_recursive_in(self, cr, s, f, w, ids):
25 #deprecated -> use _left and _right...
27 for i in range(0, len(ids), cr.IN_MAX):
28 subids = ids[i:i+cr.IN_MAX]
29 cr.execute('SELECT "%s"' \
31 ' WHERE "%s" in (%s)' % (s, f, w, ','.join(['%d']*len(subids))),
33 res.extend([r[0] for r in cr.fetchall()])
37 def __init__(self, exp):
39 # check if the expression is valid
40 if not reduce(lambda acc, val: acc and (self._is_operator(val) or self._is_leaf(val)), exp, True):
41 raise ValueError('Bad 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()
48 self.__DUMMY_LEAF = (1, '=', 1) # a dummy leaf that must not be parsed or sql generated
51 def parse(self, cr, uid, table, context):
52 """ transform the leafs of the expression """
54 def _rec_get(ids, table, parent):
57 ids2 = table.search(cr, uid, [(parent, 'in', ids)], context=context)
58 return ids + _rec_get(ids2, table, parent)
63 self.__main_table = table
66 for i, e in enumerate(self.__exp):
67 if self._is_operator(e) or e == self.__DUMMY_LEAF:
69 left, operator, right = e
71 if left in table._inherit_fields:
72 working_table = table.pool.get(table._inherit_fields[left][0])
73 if working_table not in self.__tables.values():
74 self.__joins.append('%s.%s' % (table._table, table._inherits[working_table._name]))
76 self.__tables[i] = working_table
78 fargs = left.split('.', 1)
79 field = working_table._columns.get(fargs[0], False)
81 if left == 'id' and operator == 'child_of':
82 right += _rec_get(right, working_table, working_table._parent_name)
83 self.__exp[i] = ('id', 'in', right)
86 field_obj = table.pool.get(field._obj)
88 if field._type == 'many2one':
89 right = field_obj.search(cr, uid, [(fargs[1], operator, right)], context=context)
90 self.__exp[i] = (fargs[0], 'in', right)
94 # this is a function field
96 if not field._fnct_search:
97 # the function field doesn't provide a search function and doesn't store
98 # values in the database, so we must ignore it : we generate a dummy leaf
99 self.__exp[i] = self.__DUMMY_LEAF
101 subexp = field.search(cr, uid, table, left, [self.__exp[i]])
102 # we assume that the expression is valid
103 # we create a dummy leaf for forcing the parsing of the resulting expression
105 self.__exp.insert(i + 1, self.__DUMMY_LEAF)
106 for j, se in enumerate(subexp):
107 self.__exp.insert(i + 2 + j, se)
109 # else, the value of the field is store in the database, so we search on it
112 elif field._type == 'one2many':
113 if isinstance(right, basestring):
114 ids2 = [x[0] for x in field_obj.name_search(cr, uid, right, [], operator)]
118 self.__exp[i] = ('id', '=', '0')
120 self.__exp[i] = ('id', 'in', self.__execute_recursive_in(cr, field._fields_id, field_obj._table, 'id', ids2))
122 elif field._type == 'many2many':
124 if operator == 'child_of':
125 if isinstance(right, basestring):
126 ids2 = [x[0] for x in field_obj.name_search(cr, uid, right, [], 'like')]
130 def _rec_convert(ids):
131 if field_obj == table:
133 return self.__execute_recursive_in(cr, field._id1, field._rel, field._id2, ids)
135 self.__exp[i] = ('id', 'in', _rec_convert(ids2 + _rec_get(ids2, field_obj, working_table._parent_name)))
137 if isinstance(right, basestring):
138 res_ids = [x[0] for x in field_obj.name_search(cr, uid, right, [], operator)]
140 res_ids = list(right)
141 self.__exp[i] = ('id', 'in', self.__execute_recursive_in(cr, field._id1, field._rel, field._id2, res_ids) or [0])
142 elif field._type == 'many2one':
143 if operator == 'child_of':
144 if isinstance(right, basestring):
145 ids2 = [x[0] for x in field_obj.search_name(cr, uid, right, [], 'like')]
149 self.__operator = 'in'
150 if field._obj != working_table._name:
151 right = ids2 + _rec_get(ids2, field_obj, working_table._parent_name)
153 right = ids2 + _rec_get(ids2, working_table, left)
155 self.__exp[i] = (left, 'in', right)
157 if isinstance(right, basestring):
158 res_ids = field_obj.name_search(cr, uid, right, [], operator)
159 right = map(lambda x: x[0], res_ids)
160 self.__exp[i] = (left, 'in', right)
164 if operator in ('like', 'ilike', 'not like', 'not ilike'):
165 right = '%%%s%%' % right
167 query1 = '( SELECT res_id' \
168 ' FROM ir_translation' \
172 ' AND value ' + operator + ' %s' \
175 ' FROM "' + working_table._table + '"' \
176 ' WHERE "' + left + '" ' + operator + ' %s' \
178 query2 = [working_table._name + ',' + left,
179 context.get('lang', False) or 'en_US',
185 self.__exp[i] = ('id', 'inselect', (query1, query2))
189 def __leaf_to_sql(self, leaf, table):
190 left, operator, right = leaf
192 if operator == 'inselect':
193 query = '(%s.%s in (%s))' % (table._table, left, right[0])
195 elif operator in ['in', 'not in']:
197 len_before = len(params)
198 for i in range(len_before)[::-1]:
199 if params[i] == False:
202 len_after = len(params)
203 check_nulls = len_after != len_before
208 instr = ','.join(['%d'] * len_after)
210 instr = ','.join([table._columns[left]._symbol_set[0]] * len_after)
211 query = '(%s.%s %s (%s))' % (table._table, left, operator, instr)
214 query = '(%s OR %s IS NULL)' % (query, left)
217 if right is False and operator == '=':
218 query = '%s IS NULL' % left
219 elif right is False and operator in ['<>', '!=']:
220 query = '%s IS NOT NULL' % left
223 query = '%s.id %s %%s' % (table._table, operator)
226 like = operator in ('like', 'ilike', 'not like', 'not ilike')
228 op = operator == '=like' and 'like' or operator
229 if left in table._columns:
230 format = like and '%s' or table._columns[left]._symbol_set[0]
231 query = '(%s.%s %s %s)' % (table._table, left, op, format)
233 query = "(%s.%s %s '%s')" % (table._table, left, op, right)
237 if isinstance(right, str):
239 elif isinstance(right, unicode):
240 str_utf8 = right.encode('utf-8')
242 str_utf8 = str(right)
243 params = '%%%s%%' % str_utf8
244 add_null = not str_utf8
245 elif left in table._columns:
246 params = table._columns[left]._symbol_set[1](right)
249 query = '(%s OR %s IS NULL)' % (query, left)
251 if isinstance(params, basestring):
253 return (query, params)
259 for i, e in reverse_enumerate(self.__exp):
261 table = self.__tables.has_key(i) and self.__tables[i] or self.__main_table
262 q, p = self.__leaf_to_sql(e, table)
267 stack.append('(NOT (%s))' % (stack.pop(),))
269 ops = {'&': ' AND ', '|': ' OR '}
272 stack.append('(%s %s %s)' % (q1, ops[e], q2,))
274 query = ' AND '.join(reversed(stack))
275 joins = ' AND '.join(map(lambda j: '%s.id = %s' % (self.__main_table._table, j), self.__joins))
277 query = '(%s AND (%s))' % (joins, query)
278 return (query, flatten(params))
280 def get_tables(self):
281 return ['"%s"' % t._table for t in set(self.__tables.values())]
283 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: