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