author | Adrien Di Mascio <Adrien.DiMascio@logilab.fr> |
Thu, 28 May 2009 09:20:07 +0200 | |
changeset 1977 | 606923dff11b |
parent 1922 | 1a0ddb675951 |
child 2058 | 7ef12c03447c |
child 2352 | 734eb79680e9 |
permissions | -rw-r--r-- |
0 | 1 |
"""The `ResultSet` class which is returned as result of a rql query |
2 |
||
3 |
:organization: Logilab |
|
1977
606923dff11b
big bunch of copyright / docstring update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1922
diff
changeset
|
4 |
:copyright: 2001-2009 LOGILAB S.A. (Paris, FRANCE), license is LGPL v2. |
0 | 5 |
:contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr |
1977
606923dff11b
big bunch of copyright / docstring update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1922
diff
changeset
|
6 |
:license: GNU Lesser General Public License, v2.1 - http://www.gnu.org/licenses |
0 | 7 |
""" |
8 |
__docformat__ = "restructuredtext en" |
|
9 |
||
10 |
from logilab.common.decorators import cached, clear_cache, copy_cache |
|
11 |
||
12 |
from rql import nodes |
|
13 |
||
14 |
from cubicweb import NotAnEntity |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1477
diff
changeset
|
15 |
|
0 | 16 |
|
17 |
class ResultSet(object): |
|
18 |
"""a result set wrap a RQL query result. This object implements a partial |
|
19 |
list protocol to allow direct use as a list of result rows. |
|
20 |
||
21 |
:type rowcount: int |
|
22 |
:ivar rowcount: number of rows in the result |
|
23 |
||
24 |
:type rows: list |
|
25 |
:ivar rows: list of rows of result |
|
26 |
||
27 |
:type description: list |
|
28 |
:ivar description: |
|
29 |
result's description, using the same structure as the result itself |
|
30 |
||
31 |
:type rql: str or unicode |
|
32 |
:ivar rql: the original RQL query string |
|
33 |
""" |
|
34 |
def __init__(self, results, rql, args=None, description=(), cachekey=None, |
|
35 |
rqlst=None): |
|
36 |
self.rows = results |
|
37 |
self.rowcount = results and len(results) or 0 |
|
38 |
# original query and arguments |
|
39 |
self.rql = rql |
|
40 |
self.args = args |
|
41 |
self.cachekey = cachekey |
|
42 |
# entity types for each cell (same shape as rows) |
|
43 |
# maybe discarded if specified when the query has been executed |
|
44 |
self.description = description |
|
45 |
# parsed syntax tree |
|
46 |
if rqlst is not None: |
|
47 |
rqlst.schema = None # reset schema in case of pyro transfert |
|
48 |
self._rqlst = rqlst |
|
49 |
# set to (limit, offset) when a result set is limited using the |
|
50 |
# .limit method |
|
51 |
self.limited = None |
|
52 |
# set by the cursor which returned this resultset |
|
53 |
self.vreg = None |
|
54 |
self.req = None |
|
1381
6042f1b342bb
consider kwargs in possible_actions
sylvain.thenault@logilab.fr
parents:
616
diff
changeset
|
55 |
# actions cache |
6042f1b342bb
consider kwargs in possible_actions
sylvain.thenault@logilab.fr
parents:
616
diff
changeset
|
56 |
self._rsetactions = None |
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1477
diff
changeset
|
57 |
|
0 | 58 |
def __str__(self): |
59 |
if not self.rows: |
|
60 |
return '<empty resultset %s>' % self.rql |
|
61 |
return '<resultset %s (%s rows)>' % (self.rql, len(self.rows)) |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1477
diff
changeset
|
62 |
|
0 | 63 |
def __repr__(self): |
64 |
if not self.rows: |
|
170
455ff18ef28e
use repr (instead of str) to print rql in __repr__ method of a result set
Stephanie Marcu <stephanie.marcu@logilab.fr>
parents:
0
diff
changeset
|
65 |
return '<empty resultset for %r>' % self.rql |
616
545a7e18c47f
don't display too much rset rows
sylvain.thenault@logilab.fr
parents:
572
diff
changeset
|
66 |
rows = self.rows |
545a7e18c47f
don't display too much rset rows
sylvain.thenault@logilab.fr
parents:
572
diff
changeset
|
67 |
if len(rows) > 10: |
545a7e18c47f
don't display too much rset rows
sylvain.thenault@logilab.fr
parents:
572
diff
changeset
|
68 |
rows = rows[:10] + ['...'] |
0 | 69 |
if not self.description: |
616
545a7e18c47f
don't display too much rset rows
sylvain.thenault@logilab.fr
parents:
572
diff
changeset
|
70 |
return '<resultset %r (%s rows): %s>' % (self.rql, len(self.rows), |
545a7e18c47f
don't display too much rset rows
sylvain.thenault@logilab.fr
parents:
572
diff
changeset
|
71 |
'\n'.join(str(r) for r in rows)) |
545a7e18c47f
don't display too much rset rows
sylvain.thenault@logilab.fr
parents:
572
diff
changeset
|
72 |
return '<resultset %r (%s rows): %s>' % (self.rql, len(self.rows), |
545a7e18c47f
don't display too much rset rows
sylvain.thenault@logilab.fr
parents:
572
diff
changeset
|
73 |
'\n'.join('%s (%s)' % (r, d) |
545a7e18c47f
don't display too much rset rows
sylvain.thenault@logilab.fr
parents:
572
diff
changeset
|
74 |
for r, d in zip(rows, self.description))) |
0 | 75 |
|
1381
6042f1b342bb
consider kwargs in possible_actions
sylvain.thenault@logilab.fr
parents:
616
diff
changeset
|
76 |
def possible_actions(self, **kwargs): |
6042f1b342bb
consider kwargs in possible_actions
sylvain.thenault@logilab.fr
parents:
616
diff
changeset
|
77 |
if self._rsetactions is None: |
6042f1b342bb
consider kwargs in possible_actions
sylvain.thenault@logilab.fr
parents:
616
diff
changeset
|
78 |
self._rsetactions = {} |
6042f1b342bb
consider kwargs in possible_actions
sylvain.thenault@logilab.fr
parents:
616
diff
changeset
|
79 |
if kwargs: |
6042f1b342bb
consider kwargs in possible_actions
sylvain.thenault@logilab.fr
parents:
616
diff
changeset
|
80 |
key = tuple(sorted(kwargs.iteritems())) |
6042f1b342bb
consider kwargs in possible_actions
sylvain.thenault@logilab.fr
parents:
616
diff
changeset
|
81 |
else: |
6042f1b342bb
consider kwargs in possible_actions
sylvain.thenault@logilab.fr
parents:
616
diff
changeset
|
82 |
key = None |
6042f1b342bb
consider kwargs in possible_actions
sylvain.thenault@logilab.fr
parents:
616
diff
changeset
|
83 |
try: |
6042f1b342bb
consider kwargs in possible_actions
sylvain.thenault@logilab.fr
parents:
616
diff
changeset
|
84 |
return self._rsetactions[key] |
6042f1b342bb
consider kwargs in possible_actions
sylvain.thenault@logilab.fr
parents:
616
diff
changeset
|
85 |
except KeyError: |
6042f1b342bb
consider kwargs in possible_actions
sylvain.thenault@logilab.fr
parents:
616
diff
changeset
|
86 |
actions = self.vreg.possible_vobjects('actions', self.req, self, **kwargs) |
6042f1b342bb
consider kwargs in possible_actions
sylvain.thenault@logilab.fr
parents:
616
diff
changeset
|
87 |
self._rsetactions[key] = actions |
6042f1b342bb
consider kwargs in possible_actions
sylvain.thenault@logilab.fr
parents:
616
diff
changeset
|
88 |
return actions |
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1477
diff
changeset
|
89 |
|
0 | 90 |
def __len__(self): |
91 |
"""returns the result set's size""" |
|
92 |
return self.rowcount |
|
93 |
||
94 |
def __nonzero__(self): |
|
95 |
return self.rowcount |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1477
diff
changeset
|
96 |
|
0 | 97 |
def __getitem__(self, i): |
98 |
"""returns the ith element of the result set""" |
|
99 |
return self.rows[i] #ResultSetRow(self.rows[i]) |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1477
diff
changeset
|
100 |
|
0 | 101 |
def __getslice__(self, i, j): |
102 |
"""returns slice [i:j] of the result set""" |
|
103 |
return self.rows[i:j] |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1477
diff
changeset
|
104 |
|
0 | 105 |
def __iter__(self): |
106 |
"""Returns an iterator over rows""" |
|
107 |
return iter(self.rows) |
|
108 |
||
109 |
def __add__(self, rset): |
|
110 |
# XXX buggy implementation (.rql and .args attributes at least much |
|
111 |
# probably differ) |
|
112 |
# at least rql could be fixed now that we have union and sub-queries |
|
113 |
# but I tend to think that since we have that, we should not need this |
|
114 |
# method anymore (syt) |
|
115 |
rset = ResultSet(self.rows+rset.rows, self.rql, self.args, |
|
116 |
self.description +rset.description) |
|
117 |
return self.req.decorate_rset(rset) |
|
118 |
||
119 |
def _prepare_copy(self, rows, descr): |
|
120 |
rset = ResultSet(rows, self.rql, self.args, descr) |
|
121 |
return self.req.decorate_rset(rset) |
|
122 |
||
123 |
def transformed_rset(self, transformcb): |
|
124 |
""" the result set according to a given column types |
|
125 |
||
126 |
:type transormcb: callable(row, desc) |
|
127 |
:param transformcb: |
|
128 |
a callable which should take a row and its type description as |
|
129 |
parameters, and return the transformed row and type description. |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1477
diff
changeset
|
130 |
|
0 | 131 |
|
132 |
:type col: int |
|
133 |
:param col: the column index |
|
134 |
||
135 |
:rtype: `ResultSet` |
|
136 |
""" |
|
137 |
rows, descr = [], [] |
|
138 |
rset = self._prepare_copy(rows, descr) |
|
139 |
for row, desc in zip(self.rows, self.description): |
|
140 |
nrow, ndesc = transformcb(row, desc) |
|
141 |
if ndesc: # transformcb returns None for ndesc to skip that row |
|
142 |
rows.append(nrow) |
|
143 |
descr.append(ndesc) |
|
144 |
rset.rowcount = len(rows) |
|
145 |
return rset |
|
146 |
||
147 |
def filtered_rset(self, filtercb, col=0): |
|
148 |
"""filter the result set according to a given filtercb |
|
149 |
||
150 |
:type filtercb: callable(entity) |
|
151 |
:param filtercb: |
|
152 |
a callable which should take an entity as argument and return |
|
153 |
False if it should be skipped, else True |
|
154 |
||
155 |
:type col: int |
|
156 |
:param col: the column index |
|
157 |
||
158 |
:rtype: `ResultSet` |
|
159 |
""" |
|
160 |
rows, descr = [], [] |
|
161 |
rset = self._prepare_copy(rows, descr) |
|
162 |
for i in xrange(len(self)): |
|
163 |
if not filtercb(self.get_entity(i, col)): |
|
164 |
continue |
|
165 |
rows.append(self.rows[i]) |
|
166 |
descr.append(self.description[i]) |
|
167 |
rset.rowcount = len(rows) |
|
168 |
return rset |
|
169 |
||
170 |
||
171 |
def sorted_rset(self, keyfunc, reverse=False, col=0): |
|
172 |
"""sorts the result set according to a given keyfunc |
|
173 |
||
174 |
:type keyfunc: callable(entity) |
|
175 |
:param keyfunc: |
|
176 |
a callable which should take an entity as argument and return |
|
177 |
the value used to compare and sort |
|
178 |
||
179 |
:type reverse: bool |
|
180 |
:param reverse: if the result should be reversed |
|
181 |
||
182 |
:type col: int |
|
183 |
:param col: the column index. if col = -1, the whole row are used |
|
184 |
||
185 |
:rtype: `ResultSet` |
|
186 |
""" |
|
187 |
rows, descr = [], [] |
|
188 |
rset = self._prepare_copy(rows, descr) |
|
189 |
if col >= 0: |
|
190 |
entities = sorted(enumerate(self.entities(col)), |
|
191 |
key=lambda (i, e): keyfunc(e), reverse=reverse) |
|
192 |
else: |
|
193 |
entities = sorted(enumerate(self), |
|
194 |
key=lambda (i, e): keyfunc(e), reverse=reverse) |
|
1132 | 195 |
for index, _ in entities: |
0 | 196 |
rows.append(self.rows[index]) |
197 |
descr.append(self.description[index]) |
|
198 |
rset.rowcount = len(rows) |
|
199 |
return rset |
|
200 |
||
201 |
def split_rset(self, keyfunc=None, col=0, return_dict=False): |
|
202 |
"""Splits the result set in multiple result set according to a given key |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1477
diff
changeset
|
203 |
|
0 | 204 |
:type keyfunc: callable(entity or FinalType) |
205 |
:param keyfunc: |
|
206 |
a callable which should take a value of the rset in argument and |
|
207 |
return the value used to group the value. If not define, raw value |
|
208 |
of the specified columns is used. |
|
209 |
||
210 |
:type col: int |
|
211 |
:param col: the column index. if col = -1, the whole row are used |
|
212 |
||
213 |
:type return_dict: Boolean |
|
214 |
:param return_dict: If true, the function return a mapping |
|
215 |
(key -> rset) instead of a list of rset |
|
216 |
||
217 |
:rtype: List of `ResultSet` or mapping of `ResultSet` |
|
218 |
||
219 |
""" |
|
220 |
result = [] |
|
221 |
mapping = {} |
|
222 |
for idx, line in enumerate(self): |
|
223 |
if col >= 0: |
|
224 |
try: |
|
1132 | 225 |
key = self.get_entity(idx, col) |
0 | 226 |
except NotAnEntity: |
227 |
key = line[col] |
|
228 |
else: |
|
229 |
key = line |
|
230 |
if keyfunc is not None: |
|
231 |
key = keyfunc(key) |
|
232 |
||
233 |
if key not in mapping: |
|
234 |
rows, descr = [], [] |
|
235 |
rset = self._prepare_copy(rows, descr) |
|
236 |
mapping[key] = rset |
|
237 |
result.append(rset) |
|
238 |
else: |
|
239 |
rset = mapping[key] |
|
240 |
rset.rows.append(self.rows[idx]) |
|
241 |
rset.description.append(self.description[idx]) |
|
242 |
||
243 |
||
244 |
for rset in result: |
|
245 |
rset.rowcount = len(rset.rows) |
|
246 |
if return_dict: |
|
247 |
return mapping |
|
248 |
else: |
|
249 |
return result |
|
250 |
||
251 |
def limit(self, limit, offset=0, inplace=False): |
|
252 |
"""limit the result set to the given number of rows optionaly starting |
|
253 |
from an index different than 0 |
|
254 |
||
255 |
:type limit: int |
|
256 |
:param limit: the maximum number of results |
|
257 |
||
258 |
:type offset: int |
|
259 |
:param offset: the offset index |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1477
diff
changeset
|
260 |
|
0 | 261 |
:type inplace: bool |
262 |
:param inplace: |
|
263 |
if true, the result set is modified in place, else a new result set |
|
264 |
is returned and the original is left unmodified |
|
265 |
||
266 |
:rtype: `ResultSet` |
|
267 |
""" |
|
268 |
stop = limit+offset |
|
269 |
rows = self.rows[offset:stop] |
|
270 |
descr = self.description[offset:stop] |
|
271 |
if inplace: |
|
272 |
rset = self |
|
273 |
rset.rows, rset.description = rows, descr |
|
274 |
rset.rowcount = len(rows) |
|
275 |
clear_cache(rset, 'description_struct') |
|
276 |
if offset: |
|
277 |
clear_cache(rset, 'get_entity') |
|
278 |
# we also have to fix/remove from the request entity cache entities |
|
279 |
# which get a wrong rset reference by this limit call |
|
280 |
for entity in self.req.cached_entities(): |
|
281 |
if entity.rset is self: |
|
282 |
if offset <= entity.row < stop: |
|
283 |
entity.row = entity.row - offset |
|
284 |
else: |
|
285 |
self.req.drop_entity_cache(entity.eid) |
|
286 |
else: |
|
287 |
rset = self._prepare_copy(rows, descr) |
|
288 |
if not offset: |
|
289 |
# can copy built entity caches |
|
290 |
copy_cache(rset, 'get_entity', self) |
|
291 |
rset.limited = (limit, offset) |
|
292 |
return rset |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1477
diff
changeset
|
293 |
|
0 | 294 |
def printable_rql(self, encoded=False): |
295 |
"""return the result set's origin rql as a string, with arguments |
|
296 |
substitued |
|
297 |
""" |
|
298 |
encoding = self.req.encoding |
|
299 |
rqlstr = self.syntax_tree().as_string(encoding, self.args) |
|
300 |
# sounds like we get encoded or unicode string due to a bug in as_string |
|
301 |
if not encoded: |
|
302 |
if isinstance(rqlstr, unicode): |
|
303 |
return rqlstr |
|
304 |
return unicode(rqlstr, encoding) |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1477
diff
changeset
|
305 |
else: |
0 | 306 |
if isinstance(rqlstr, unicode): |
307 |
return rqlstr.encode(encoding) |
|
308 |
return rqlstr |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1477
diff
changeset
|
309 |
|
0 | 310 |
# client helper methods ################################################### |
311 |
||
312 |
def entities(self, col=0): |
|
313 |
"""iter on entities with eid in the `col` column of the result set""" |
|
314 |
for i in xrange(len(self)): |
|
315 |
# may have None values in case of outer join (or aggregat on eid |
|
316 |
# hacks) |
|
317 |
if self.rows[i][col] is not None: |
|
318 |
yield self.get_entity(i, col) |
|
319 |
||
320 |
@cached |
|
321 |
def get_entity(self, row, col=None): |
|
322 |
"""special method for query retreiving a single entity, returns a |
|
323 |
partially initialized Entity instance. |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1477
diff
changeset
|
324 |
|
0 | 325 |
WARNING: due to the cache wrapping this function, you should NEVER |
326 |
give row as a named parameter (i.e. rset.get_entity(req, 0) |
|
327 |
is OK but rset.get_entity(row=0, req=req) isn't |
|
328 |
||
329 |
:type row,col: int, int |
|
330 |
:param row,col: |
|
331 |
row and col numbers localizing the entity among the result's table |
|
332 |
||
333 |
:return: the partially initialized `Entity` instance |
|
334 |
""" |
|
335 |
if col is None: |
|
336 |
from warnings import warn |
|
337 |
msg = 'col parameter will become mandatory in future version' |
|
338 |
warn(msg, DeprecationWarning, stacklevel=3) |
|
339 |
col = 0 |
|
340 |
etype = self.description[row][col] |
|
341 |
try: |
|
342 |
eschema = self.vreg.schema.eschema(etype) |
|
343 |
if eschema.is_final(): |
|
344 |
raise NotAnEntity(etype) |
|
345 |
except KeyError: |
|
346 |
raise NotAnEntity(etype) |
|
347 |
return self._build_entity(row, col) |
|
348 |
||
349 |
def _build_entity(self, row, col, _localcache=None): |
|
350 |
"""internal method to get a single entity, returns a |
|
351 |
partially initialized Entity instance. |
|
352 |
||
353 |
partially means that only attributes selected in the RQL |
|
354 |
query will be directly assigned to the entity. |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1477
diff
changeset
|
355 |
|
0 | 356 |
:type row,col: int, int |
357 |
:param row,col: |
|
358 |
row and col numbers localizing the entity among the result's table |
|
359 |
||
360 |
:return: the partially initialized `Entity` instance |
|
361 |
""" |
|
362 |
req = self.req |
|
363 |
if req is None: |
|
364 |
raise AssertionError('dont call get_entity with no req on the result set') |
|
365 |
rowvalues = self.rows[row] |
|
366 |
eid = rowvalues[col] |
|
367 |
assert eid is not None |
|
368 |
# return cached entity if exists. This also avoids potential recursion |
|
369 |
# XXX should we consider updating a cached entity with possible |
|
370 |
# new attributes found in this resultset ? |
|
371 |
try: |
|
372 |
if hasattr(req, 'is_super_session'): |
|
373 |
# this is a Session object which is not caching entities, so we |
|
374 |
# have to use a local cache to avoid recursion pb |
|
375 |
if _localcache is None: |
|
376 |
_localcache = {} |
|
377 |
return _localcache[eid] |
|
378 |
else: |
|
379 |
return req.entity_cache(eid) |
|
380 |
except KeyError: |
|
381 |
pass |
|
382 |
# build entity instance |
|
383 |
etype = self.description[row][col] |
|
384 |
entity = self.vreg.etype_class(etype)(req, self, row, col) |
|
385 |
entity.set_eid(eid) |
|
386 |
# cache entity |
|
387 |
if _localcache is not None: |
|
388 |
_localcache[eid] = entity |
|
389 |
req.set_entity_cache(entity) |
|
390 |
eschema = entity.e_schema |
|
391 |
# try to complete the entity if there are some additional columns |
|
392 |
if len(rowvalues) > 1: |
|
393 |
rqlst = self.syntax_tree() |
|
394 |
if rqlst.TYPE == 'select': |
|
395 |
# UNION query, find the subquery from which this entity has been |
|
396 |
# found |
|
397 |
rqlst = rqlst.locate_subquery(col, etype, self.args) |
|
398 |
# take care, due to outer join support, we may find None |
|
399 |
# values for non final relation |
|
400 |
for i, attr, x in attr_desc_iterator(rqlst, col): |
|
401 |
if x == 'subject': |
|
402 |
rschema = eschema.subject_relation(attr) |
|
403 |
if rschema.is_final(): |
|
404 |
entity[attr] = rowvalues[i] |
|
405 |
continue |
|
406 |
tetype = rschema.objects(etype)[0] |
|
407 |
card = rschema.rproperty(etype, tetype, 'cardinality')[0] |
|
408 |
else: |
|
409 |
rschema = eschema.object_relation(attr) |
|
410 |
tetype = rschema.subjects(etype)[0] |
|
411 |
card = rschema.rproperty(tetype, etype, 'cardinality')[1] |
|
412 |
# only keep value if it can't be multivalued |
|
413 |
if card in '1?': |
|
414 |
if rowvalues[i] is None: |
|
415 |
if x == 'subject': |
|
416 |
rql = 'Any Y WHERE X %s Y, X eid %s' |
|
417 |
else: |
|
418 |
rql = 'Any Y WHERE Y %s X, X eid %s' |
|
419 |
rrset = ResultSet([], rql % (attr, entity.eid)) |
|
420 |
req.decorate_rset(rrset) |
|
421 |
else: |
|
422 |
rrset = self._build_entity(row, i, _localcache).as_rset() |
|
423 |
entity.set_related_cache(attr, x, rrset) |
|
424 |
return entity |
|
425 |
||
426 |
@cached |
|
427 |
def syntax_tree(self): |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1477
diff
changeset
|
428 |
"""get the syntax tree for the source query. |
0 | 429 |
|
430 |
:rtype: rql.stmts.Statement |
|
431 |
:return: the RQL syntax tree of the originating query |
|
432 |
""" |
|
433 |
if self._rqlst: |
|
434 |
rqlst = self._rqlst.copy() |
|
435 |
# to avoid transport overhead when pyro is used, the schema has been |
|
436 |
# unset from the syntax tree |
|
437 |
rqlst.schema = self.vreg.schema |
|
438 |
self.vreg.rqlhelper.annotate(rqlst) |
|
439 |
else: |
|
440 |
rqlst = self.vreg.parse(self.req, self.rql, self.args) |
|
441 |
return rqlst |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1477
diff
changeset
|
442 |
|
0 | 443 |
@cached |
444 |
def column_types(self, col): |
|
445 |
"""return the list of different types in the column with the given col |
|
446 |
index default to 0 (ie the first column) |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1477
diff
changeset
|
447 |
|
0 | 448 |
:type col: int |
449 |
:param col: the index of the desired column |
|
450 |
||
451 |
:rtype: list |
|
452 |
:return: the different entities type found in the column |
|
453 |
""" |
|
454 |
return frozenset(struc[-1][col] for struc in self.description_struct()) |
|
455 |
||
456 |
@cached |
|
457 |
def description_struct(self): |
|
458 |
"""return a list describing sequence of results with the same |
|
459 |
description, e.g. : |
|
460 |
[[0, 4, ('Bug',)] |
|
461 |
[[0, 4, ('Bug',), [5, 8, ('Story',)] |
|
462 |
[[0, 3, ('Project', 'Version',)]] |
|
463 |
""" |
|
464 |
result = [] |
|
465 |
last = None |
|
466 |
for i, row in enumerate(self.description): |
|
467 |
if row != last: |
|
468 |
if last is not None: |
|
469 |
result[-1][1] = i - 1 |
|
470 |
result.append( [i, None, row] ) |
|
471 |
last = row |
|
472 |
if last is not None: |
|
473 |
result[-1][1] = i |
|
474 |
return result |
|
475 |
||
476 |
@cached |
|
477 |
def related_entity(self, row, col): |
|
478 |
"""try to get the related entity to extract format information if any""" |
|
479 |
locate_query_col = col |
|
480 |
rqlst = self.syntax_tree() |
|
481 |
etype = self.description[row][col] |
|
482 |
if self.vreg.schema.eschema(etype).is_final(): |
|
572
9849fed789c9
test and fix potential error with None optional relation
sylvain.thenault@logilab.fr
parents:
170
diff
changeset
|
483 |
# final type, find a better one to locate the correct subquery |
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1477
diff
changeset
|
484 |
# (ambiguous if possible) |
0 | 485 |
for i in xrange(len(rqlst.children[0].selection)): |
486 |
if i == col: |
|
487 |
continue |
|
488 |
coletype = self.description[row][i] |
|
489 |
if coletype is None: |
|
490 |
continue |
|
491 |
if not self.vreg.schema.eschema(coletype).is_final(): |
|
492 |
etype = coletype |
|
493 |
locate_query_col = i |
|
494 |
if len(self.column_types(i)) > 1: |
|
495 |
break |
|
572
9849fed789c9
test and fix potential error with None optional relation
sylvain.thenault@logilab.fr
parents:
170
diff
changeset
|
496 |
# UNION query, find the subquery from which this entity has been found |
0 | 497 |
select = rqlst.locate_subquery(locate_query_col, etype, self.args) |
498 |
try: |
|
499 |
myvar = select.selection[col].variable |
|
500 |
except AttributeError: |
|
572
9849fed789c9
test and fix potential error with None optional relation
sylvain.thenault@logilab.fr
parents:
170
diff
changeset
|
501 |
# not a variable |
0 | 502 |
return None, None |
503 |
rel = myvar.main_relation() |
|
504 |
if rel is not None: |
|
505 |
index = rel.children[0].variable.selected_index() |
|
572
9849fed789c9
test and fix potential error with None optional relation
sylvain.thenault@logilab.fr
parents:
170
diff
changeset
|
506 |
if index is not None and self.rows[row][index]: |
0 | 507 |
return self.get_entity(row, index), rel.r_type |
508 |
return None, None |
|
509 |
||
510 |
@cached |
|
511 |
def searched_text(self): |
|
512 |
"""returns the searched text in case of full-text search |
|
513 |
||
514 |
:return: searched text or `None` if the query is not |
|
515 |
a full-text query |
|
516 |
""" |
|
517 |
rqlst = self.syntax_tree() |
|
518 |
for rel in rqlst.iget_nodes(nodes.Relation): |
|
519 |
if rel.r_type == 'has_text': |
|
520 |
__, rhs = rel.get_variable_parts() |
|
521 |
return rhs.eval(self.args) |
|
522 |
return None |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1477
diff
changeset
|
523 |
|
0 | 524 |
|
525 |
def attr_desc_iterator(rqlst, index=0): |
|
526 |
"""return an iterator on a list of 2-uple (index, attr_relation) |
|
527 |
localizing attribute relations of the main variable in a result's row |
|
528 |
||
529 |
:type rqlst: rql.stmts.Select |
|
530 |
:param rqlst: the RQL syntax tree to describe |
|
531 |
||
532 |
:return: |
|
533 |
a generator on (index, relation, target) describing column being |
|
534 |
attribute of the main variable |
|
535 |
""" |
|
536 |
main = rqlst.selection[index] |
|
537 |
for i, term in enumerate(rqlst.selection): |
|
538 |
if i == index: |
|
539 |
continue |
|
540 |
try: |
|
541 |
# XXX rewritten const |
|
542 |
var = term.variable |
|
543 |
except AttributeError: |
|
544 |
continue |
|
545 |
#varname = var.name |
|
546 |
for ref in var.references(): |
|
547 |
rel = ref.relation() |
|
548 |
if rel is None or rel.is_types_restriction(): |
|
549 |
continue |
|
550 |
lhs, rhs = rel.get_variable_parts() |
|
551 |
if main.is_equivalent(lhs): |
|
552 |
if rhs.is_equivalent(term): |
|
553 |
yield (i, rel.r_type, 'subject') |
|
554 |
elif main.is_equivalent(rhs): |
|
555 |
if lhs.is_equivalent(term): |
|
556 |
yield (i, rel.r_type, 'object') |