author | Sylvain <syt@logilab.fr> |
Thu, 14 May 2009 14:51:52 +0200 | |
changeset 1819 | 7d3e8adcd559 |
parent 1802 | d628defebc17 |
child 1922 | 1a0ddb675951 |
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] |
|
1398
5fe84a5f7035
rename internal entity types to have CW prefix instead of E
sylvain.thenault@logilab.fr
parents:
1132
diff
changeset
|
383 |
if etype == 'EUser': |
5fe84a5f7035
rename internal entity types to have CW prefix instead of E
sylvain.thenault@logilab.fr
parents:
1132
diff
changeset
|
384 |
import traceback |
5fe84a5f7035
rename internal entity types to have CW prefix instead of E
sylvain.thenault@logilab.fr
parents:
1132
diff
changeset
|
385 |
traceback.printstack() |
0 | 386 |
entity = self.vreg.etype_class(etype)(req, self, row, col) |
387 |
entity.set_eid(eid) |
|
388 |
# cache entity |
|
389 |
if _localcache is not None: |
|
390 |
_localcache[eid] = entity |
|
391 |
req.set_entity_cache(entity) |
|
392 |
eschema = entity.e_schema |
|
393 |
# try to complete the entity if there are some additional columns |
|
394 |
if len(rowvalues) > 1: |
|
395 |
rqlst = self.syntax_tree() |
|
396 |
if rqlst.TYPE == 'select': |
|
397 |
# UNION query, find the subquery from which this entity has been |
|
398 |
# found |
|
399 |
rqlst = rqlst.locate_subquery(col, etype, self.args) |
|
400 |
# take care, due to outer join support, we may find None |
|
401 |
# values for non final relation |
|
402 |
for i, attr, x in attr_desc_iterator(rqlst, col): |
|
403 |
if x == 'subject': |
|
404 |
rschema = eschema.subject_relation(attr) |
|
405 |
if rschema.is_final(): |
|
406 |
entity[attr] = rowvalues[i] |
|
407 |
continue |
|
408 |
tetype = rschema.objects(etype)[0] |
|
409 |
card = rschema.rproperty(etype, tetype, 'cardinality')[0] |
|
410 |
else: |
|
411 |
rschema = eschema.object_relation(attr) |
|
412 |
tetype = rschema.subjects(etype)[0] |
|
413 |
card = rschema.rproperty(tetype, etype, 'cardinality')[1] |
|
414 |
# only keep value if it can't be multivalued |
|
415 |
if card in '1?': |
|
416 |
if rowvalues[i] is None: |
|
417 |
if x == 'subject': |
|
418 |
rql = 'Any Y WHERE X %s Y, X eid %s' |
|
419 |
else: |
|
420 |
rql = 'Any Y WHERE Y %s X, X eid %s' |
|
421 |
rrset = ResultSet([], rql % (attr, entity.eid)) |
|
422 |
req.decorate_rset(rrset) |
|
423 |
else: |
|
424 |
rrset = self._build_entity(row, i, _localcache).as_rset() |
|
425 |
entity.set_related_cache(attr, x, rrset) |
|
426 |
return entity |
|
427 |
||
428 |
@cached |
|
429 |
def syntax_tree(self): |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1477
diff
changeset
|
430 |
"""get the syntax tree for the source query. |
0 | 431 |
|
432 |
:rtype: rql.stmts.Statement |
|
433 |
:return: the RQL syntax tree of the originating query |
|
434 |
""" |
|
435 |
if self._rqlst: |
|
436 |
rqlst = self._rqlst.copy() |
|
437 |
# to avoid transport overhead when pyro is used, the schema has been |
|
438 |
# unset from the syntax tree |
|
439 |
rqlst.schema = self.vreg.schema |
|
440 |
self.vreg.rqlhelper.annotate(rqlst) |
|
441 |
else: |
|
442 |
rqlst = self.vreg.parse(self.req, self.rql, self.args) |
|
443 |
return rqlst |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1477
diff
changeset
|
444 |
|
0 | 445 |
@cached |
446 |
def column_types(self, col): |
|
447 |
"""return the list of different types in the column with the given col |
|
448 |
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
|
449 |
|
0 | 450 |
:type col: int |
451 |
:param col: the index of the desired column |
|
452 |
||
453 |
:rtype: list |
|
454 |
:return: the different entities type found in the column |
|
455 |
""" |
|
456 |
return frozenset(struc[-1][col] for struc in self.description_struct()) |
|
457 |
||
458 |
@cached |
|
459 |
def description_struct(self): |
|
460 |
"""return a list describing sequence of results with the same |
|
461 |
description, e.g. : |
|
462 |
[[0, 4, ('Bug',)] |
|
463 |
[[0, 4, ('Bug',), [5, 8, ('Story',)] |
|
464 |
[[0, 3, ('Project', 'Version',)]] |
|
465 |
""" |
|
466 |
result = [] |
|
467 |
last = None |
|
468 |
for i, row in enumerate(self.description): |
|
469 |
if row != last: |
|
470 |
if last is not None: |
|
471 |
result[-1][1] = i - 1 |
|
472 |
result.append( [i, None, row] ) |
|
473 |
last = row |
|
474 |
if last is not None: |
|
475 |
result[-1][1] = i |
|
476 |
return result |
|
477 |
||
478 |
@cached |
|
479 |
def related_entity(self, row, col): |
|
480 |
"""try to get the related entity to extract format information if any""" |
|
481 |
locate_query_col = col |
|
482 |
rqlst = self.syntax_tree() |
|
483 |
etype = self.description[row][col] |
|
484 |
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
|
485 |
# 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
|
486 |
# (ambiguous if possible) |
0 | 487 |
for i in xrange(len(rqlst.children[0].selection)): |
488 |
if i == col: |
|
489 |
continue |
|
490 |
coletype = self.description[row][i] |
|
491 |
if coletype is None: |
|
492 |
continue |
|
493 |
if not self.vreg.schema.eschema(coletype).is_final(): |
|
494 |
etype = coletype |
|
495 |
locate_query_col = i |
|
496 |
if len(self.column_types(i)) > 1: |
|
497 |
break |
|
572
9849fed789c9
test and fix potential error with None optional relation
sylvain.thenault@logilab.fr
parents:
170
diff
changeset
|
498 |
# UNION query, find the subquery from which this entity has been found |
0 | 499 |
select = rqlst.locate_subquery(locate_query_col, etype, self.args) |
500 |
try: |
|
501 |
myvar = select.selection[col].variable |
|
502 |
except AttributeError: |
|
572
9849fed789c9
test and fix potential error with None optional relation
sylvain.thenault@logilab.fr
parents:
170
diff
changeset
|
503 |
# not a variable |
0 | 504 |
return None, None |
505 |
rel = myvar.main_relation() |
|
506 |
if rel is not None: |
|
507 |
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
|
508 |
if index is not None and self.rows[row][index]: |
0 | 509 |
return self.get_entity(row, index), rel.r_type |
510 |
return None, None |
|
511 |
||
512 |
@cached |
|
513 |
def searched_text(self): |
|
514 |
"""returns the searched text in case of full-text search |
|
515 |
||
516 |
:return: searched text or `None` if the query is not |
|
517 |
a full-text query |
|
518 |
""" |
|
519 |
rqlst = self.syntax_tree() |
|
520 |
for rel in rqlst.iget_nodes(nodes.Relation): |
|
521 |
if rel.r_type == 'has_text': |
|
522 |
__, rhs = rel.get_variable_parts() |
|
523 |
return rhs.eval(self.args) |
|
524 |
return None |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1477
diff
changeset
|
525 |
|
0 | 526 |
|
527 |
def attr_desc_iterator(rqlst, index=0): |
|
528 |
"""return an iterator on a list of 2-uple (index, attr_relation) |
|
529 |
localizing attribute relations of the main variable in a result's row |
|
530 |
||
531 |
:type rqlst: rql.stmts.Select |
|
532 |
:param rqlst: the RQL syntax tree to describe |
|
533 |
||
534 |
:return: |
|
535 |
a generator on (index, relation, target) describing column being |
|
536 |
attribute of the main variable |
|
537 |
""" |
|
538 |
main = rqlst.selection[index] |
|
539 |
for i, term in enumerate(rqlst.selection): |
|
540 |
if i == index: |
|
541 |
continue |
|
542 |
try: |
|
543 |
# XXX rewritten const |
|
544 |
var = term.variable |
|
545 |
except AttributeError: |
|
546 |
continue |
|
547 |
#varname = var.name |
|
548 |
for ref in var.references(): |
|
549 |
rel = ref.relation() |
|
550 |
if rel is None or rel.is_types_restriction(): |
|
551 |
continue |
|
552 |
lhs, rhs = rel.get_variable_parts() |
|
553 |
if main.is_equivalent(lhs): |
|
554 |
if rhs.is_equivalent(term): |
|
555 |
yield (i, rel.r_type, 'subject') |
|
556 |
elif main.is_equivalent(rhs): |
|
557 |
if lhs.is_equivalent(term): |
|
558 |
yield (i, rel.r_type, 'object') |