author | Nicolas Chauvat <nicolas.chauvat@logilab.fr> |
Sun, 27 Sep 2009 14:37:55 +0200 | |
branch | stable |
changeset 3488 | ab9e7bcfc764 |
parent 3249 | 280080eadb22 |
child 3689 | deb13e88e037 |
permissions | -rw-r--r-- |
0 | 1 |
"""Functions to add additional annotations on a rql syntax tree to ease later |
2 |
code generation. |
|
3 |
||
4 |
:organization: Logilab |
|
1977
606923dff11b
big bunch of copyright / docstring update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1802
diff
changeset
|
5 |
:copyright: 2001-2009 LOGILAB S.A. (Paris, FRANCE), license is LGPL v2. |
0 | 6 |
: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:
1802
diff
changeset
|
7 |
:license: GNU Lesser General Public License, v2.1 - http://www.gnu.org/licenses |
0 | 8 |
""" |
9 |
__docformat__ = "restructuredtext en" |
|
10 |
||
11 |
from logilab.common.compat import any |
|
12 |
||
1132 | 13 |
from rql.nodes import Relation, VariableRef, Constant, Variable, Or |
0 | 14 |
from rql.utils import common_parent |
15 |
||
16 |
def _annotate_select(annotator, rqlst): |
|
17 |
for subquery in rqlst.with_: |
|
18 |
annotator._annotate_union(subquery.query) |
|
19 |
#if server.DEBUG: |
|
20 |
# print '-------- sql annotate', repr(rqlst) |
|
21 |
getrschema = annotator.schema.rschema |
|
438 | 22 |
has_text_query = False |
0 | 23 |
need_distinct = rqlst.distinct |
24 |
for rel in rqlst.iget_nodes(Relation): |
|
2353
b11f1068a0d3
fix regression w/ NOT symetric relation (distinct not needed)
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2199
diff
changeset
|
25 |
if getrschema(rel.r_type).symetric and not rel.neged(strict=True): |
0 | 26 |
for vref in rel.iget_nodes(VariableRef): |
27 |
stinfo = vref.variable.stinfo |
|
28 |
if not stinfo['constnode'] and stinfo['selected']: |
|
29 |
need_distinct = True |
|
30 |
# XXX could mark as not invariant |
|
31 |
break |
|
32 |
for name, var in rqlst.defined_vars.items(): |
|
33 |
stinfo = var.stinfo |
|
34 |
if stinfo.get('ftirels'): |
|
35 |
has_text_query = True |
|
36 |
if stinfo['attrvar']: |
|
37 |
stinfo['invariant'] = False |
|
38 |
stinfo['principal'] = _select_main_var(stinfo['rhsrelations']) |
|
39 |
continue |
|
40 |
if not stinfo['relations'] and not stinfo['typerels']: |
|
41 |
# Any X, Any MAX(X)... |
|
42 |
# those particular queries should be executed using the system |
|
43 |
# entities table unless there is some type restriction |
|
44 |
stinfo['invariant'] = True |
|
45 |
stinfo['principal'] = None |
|
46 |
continue |
|
47 |
if any(rel for rel in stinfo['relations'] if rel.r_type == 'eid' and rel.operator() != '=') and \ |
|
48 |
not any(r for r in var.stinfo['relations'] - var.stinfo['rhsrelations'] |
|
49 |
if r.r_type != 'eid' and (getrschema(r.r_type).inlined or getrschema(r.r_type).final)): |
|
50 |
# Any X WHERE X eid > 2 |
|
51 |
# those particular queries should be executed using the system entities table |
|
52 |
stinfo['invariant'] = True |
|
53 |
stinfo['principal'] = None |
|
54 |
continue |
|
55 |
if stinfo['selected'] and var.valuable_references() == 1+bool(stinfo['constnode']): |
|
56 |
# "Any X", "Any X, Y WHERE X attr Y" |
|
57 |
stinfo['invariant'] = False |
|
58 |
continue |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1132
diff
changeset
|
59 |
joins = set() |
0 | 60 |
invariant = False |
61 |
for ref in var.references(): |
|
62 |
rel = ref.relation() |
|
63 |
if rel is None or rel.is_types_restriction(): |
|
64 |
continue |
|
65 |
lhs, rhs = rel.get_parts() |
|
66 |
onlhs = ref is lhs |
|
67 |
if rel.r_type == 'eid': |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1132
diff
changeset
|
68 |
if not (onlhs and len(stinfo['relations']) > 1): |
0 | 69 |
break |
70 |
if not stinfo['constnode']: |
|
71 |
joins.add(rel) |
|
72 |
continue |
|
73 |
elif rel.r_type == 'identity': |
|
74 |
# identity can't be used as principal, so check other relation are used |
|
75 |
# XXX explain rhs.operator == '=' |
|
76 |
if rhs.operator != '=' or len(stinfo['relations']) <= 1: #(stinfo['constnode'] and rhs.operator == '='): |
|
77 |
break |
|
78 |
joins.add(rel) |
|
79 |
continue |
|
80 |
rschema = getrschema(rel.r_type) |
|
81 |
if rel.optional: |
|
82 |
if rel in stinfo['optrelations']: |
|
83 |
# optional variable can't be invariant if this is the lhs |
|
84 |
# variable of an inlined relation |
|
85 |
if not rel in stinfo['rhsrelations'] and rschema.inlined: |
|
86 |
break |
|
87 |
else: |
|
88 |
# variable used as main variable of an optional relation |
|
89 |
# can't be invariant |
|
90 |
break |
|
91 |
if rschema.final or (onlhs and rschema.inlined): |
|
92 |
if rschema.type != 'has_text': |
|
93 |
# need join anyway if the variable appears in a final or |
|
94 |
# inlined relation |
|
95 |
break |
|
96 |
joins.add(rel) |
|
97 |
continue |
|
98 |
if not stinfo['constnode']: |
|
99 |
if rschema.inlined and rel.neged(strict=True): |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1132
diff
changeset
|
100 |
# if relation is inlined, can't be invariant if that |
0 | 101 |
# variable is used anywhere else. |
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1132
diff
changeset
|
102 |
# see 'Any P WHERE NOT N ecrit_par P, N eid 512': |
0 | 103 |
# sql for 'NOT N ecrit_par P' is 'N.ecrit_par is NULL' so P |
104 |
# can use N.ecrit_par as principal |
|
105 |
if (stinfo['selected'] or len(stinfo['relations']) > 1): |
|
106 |
break |
|
107 |
elif rschema.symetric and stinfo['selected']: |
|
108 |
break |
|
109 |
joins.add(rel) |
|
110 |
else: |
|
111 |
# if there is at least one ambigous relation and no other to |
|
112 |
# restrict types, can't be invariant since we need to filter out |
|
113 |
# other types |
|
114 |
if not annotator.is_ambiguous(var): |
|
115 |
invariant = True |
|
116 |
stinfo['invariant'] = invariant |
|
117 |
if invariant and joins: |
|
118 |
# remember rqlst/solutions analyze information |
|
119 |
# we have to select a kindof "main" relation which will "extrajoins" |
|
120 |
# the other |
|
121 |
# priority should be given to relation which are not in inner queries |
|
122 |
# (eg exists) |
|
123 |
try: |
|
124 |
stinfo['principal'] = _select_principal(var.sqlscope, joins) |
|
125 |
except CantSelectPrincipal: |
|
126 |
stinfo['invariant'] = False |
|
127 |
rqlst.need_distinct = need_distinct |
|
128 |
return has_text_query |
|
129 |
||
130 |
||
131 |
||
132 |
class CantSelectPrincipal(Exception): pass |
|
133 |
||
599
9ef680acd92a
fix select principal so results are predictable during tests
Sylvain <syt@logilab.fr>
parents:
438
diff
changeset
|
134 |
def _select_principal(sqlscope, relations, _sort=lambda x:x): |
0 | 135 |
"""given a list of rqlst relations, select one which will be used to |
136 |
represent an invariant variable (e.g. using on extremity of the relation |
|
137 |
instead of the variable's type table |
|
138 |
""" |
|
599
9ef680acd92a
fix select principal so results are predictable during tests
Sylvain <syt@logilab.fr>
parents:
438
diff
changeset
|
139 |
# _sort argument is there for test |
0 | 140 |
diffscope_rels = {} |
141 |
has_same_scope_rel = False |
|
142 |
ored_rels = set() |
|
143 |
diffscope_rels = set() |
|
599
9ef680acd92a
fix select principal so results are predictable during tests
Sylvain <syt@logilab.fr>
parents:
438
diff
changeset
|
144 |
for rel in _sort(relations): |
0 | 145 |
# note: only eid and has_text among all final relations may be there |
146 |
if rel.r_type in ('eid', 'identity'): |
|
147 |
has_same_scope_rel = rel.sqlscope is sqlscope |
|
148 |
continue |
|
149 |
if rel.ored(traverse_scope=True): |
|
150 |
ored_rels.add(rel) |
|
151 |
elif rel.sqlscope is sqlscope: |
|
152 |
return rel |
|
153 |
elif not rel.neged(traverse_scope=True): |
|
154 |
diffscope_rels.add(rel) |
|
155 |
if len(ored_rels) > 1: |
|
156 |
ored_rels_copy = tuple(ored_rels) |
|
157 |
for rel1 in ored_rels_copy: |
|
158 |
for rel2 in ored_rels_copy: |
|
159 |
if rel1 is rel2: |
|
160 |
continue |
|
161 |
if isinstance(common_parent(rel1, rel2), Or): |
|
162 |
ored_rels.discard(rel1) |
|
163 |
ored_rels.discard(rel2) |
|
599
9ef680acd92a
fix select principal so results are predictable during tests
Sylvain <syt@logilab.fr>
parents:
438
diff
changeset
|
164 |
for rel in _sort(ored_rels): |
0 | 165 |
if rel.sqlscope is sqlscope: |
166 |
return rel |
|
167 |
diffscope_rels.add(rel) |
|
168 |
# if DISTINCT query, can use variable from a different scope as principal |
|
169 |
# since introduced duplicates will be removed |
|
170 |
if sqlscope.stmt.distinct and diffscope_rels: |
|
599
9ef680acd92a
fix select principal so results are predictable during tests
Sylvain <syt@logilab.fr>
parents:
438
diff
changeset
|
171 |
return iter(_sort(diffscope_rels)).next() |
0 | 172 |
# XXX could use a relation for a different scope if it can't generate |
173 |
# duplicates, so we would have to check cardinality |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1132
diff
changeset
|
174 |
raise CantSelectPrincipal() |
0 | 175 |
|
176 |
def _select_main_var(relations): |
|
177 |
"""given a list of rqlst relations, select one which will be used as main |
|
178 |
relation for the rhs variable |
|
179 |
""" |
|
180 |
for rel in relations: |
|
181 |
if rel.sqlscope is rel.stmt: |
|
182 |
return rel |
|
183 |
principal = rel |
|
184 |
return principal |
|
185 |
||
186 |
||
438 | 187 |
def set_qdata(getrschema, union, noinvariant): |
0 | 188 |
"""recursive function to set querier data on variables in the syntax tree |
189 |
""" |
|
190 |
for select in union.children: |
|
191 |
for subquery in select.with_: |
|
438 | 192 |
set_qdata(getrschema, subquery.query, noinvariant) |
0 | 193 |
for var in select.defined_vars.itervalues(): |
194 |
if var.stinfo['invariant']: |
|
195 |
if var in noinvariant and not var.stinfo['principal'].r_type == 'has_text': |
|
196 |
var._q_invariant = False |
|
197 |
else: |
|
198 |
var._q_invariant = True |
|
199 |
else: |
|
200 |
var._q_invariant = False |
|
438 | 201 |
for rel in select.iget_nodes(Relation): |
202 |
if rel.neged(strict=True) and not rel.is_types_restriction(): |
|
203 |
rschema = getrschema(rel.r_type) |
|
204 |
if not rschema.is_final(): |
|
205 |
# if one of the relation's variable is ambiguous but not |
|
206 |
# invariant, an intersection will be necessary |
|
207 |
for vref in rel.get_nodes(VariableRef): |
|
208 |
var = vref.variable |
|
209 |
if (not var._q_invariant and var.valuable_references() == 1 |
|
210 |
and len(var.stinfo['possibletypes']) > 1): |
|
211 |
select.need_intersect = True |
|
212 |
break |
|
213 |
else: |
|
214 |
continue |
|
215 |
break |
|
216 |
else: |
|
217 |
select.need_intersect = False |
|
0 | 218 |
|
219 |
||
220 |
class SQLGenAnnotator(object): |
|
221 |
def __init__(self, schema): |
|
222 |
self.schema = schema |
|
223 |
self.nfdomain = frozenset(eschema.type for eschema in schema.entities() |
|
224 |
if not eschema.is_final()) |
|
225 |
||
226 |
def annotate(self, rqlst): |
|
227 |
"""add information to the rql syntax tree to help sources to do their |
|
228 |
job (read sql generation) |
|
229 |
||
230 |
a variable is tagged as invariant if: |
|
231 |
* it's a non final variable |
|
232 |
* it's not used as lhs in any final or inlined relation |
|
233 |
* there is no type restriction on this variable (either explicit in the |
|
234 |
syntax tree or because a solution for this variable has been removed |
|
235 |
due to security filtering) |
|
236 |
""" |
|
237 |
assert rqlst.TYPE == 'select', rqlst |
|
238 |
rqlst.has_text_query = self._annotate_union(rqlst) |
|
239 |
||
240 |
def _annotate_union(self, union): |
|
241 |
has_text_query = False |
|
242 |
for select in union.children: |
|
243 |
htq = _annotate_select(self, select) |
|
244 |
if htq: |
|
245 |
has_text_query = True |
|
246 |
return has_text_query |
|
247 |
||
248 |
def is_ambiguous(self, var): |
|
249 |
# ignore has_text relation |
|
250 |
if len([rel for rel in var.stinfo['relations'] |
|
251 |
if rel.sqlscope is var.sqlscope and rel.r_type == 'has_text']) == 1: |
|
252 |
return False |
|
253 |
try: |
|
254 |
data = var.stmt._deamb_data |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1132
diff
changeset
|
255 |
except AttributeError: |
0 | 256 |
data = var.stmt._deamb_data = IsAmbData(self.schema, self.nfdomain) |
257 |
data.compute(var.stmt) |
|
258 |
return data.is_ambiguous(var) |
|
259 |
||
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1132
diff
changeset
|
260 |
|
0 | 261 |
class IsAmbData(object): |
262 |
def __init__(self, schema, nfdomain): |
|
263 |
self.schema = schema |
|
264 |
# shortcuts |
|
265 |
self.rschema = schema.rschema |
|
266 |
self.eschema = schema.eschema |
|
267 |
# domain for non final variables |
|
268 |
self.nfdomain = nfdomain |
|
269 |
# {var: possible solutions set} |
|
270 |
self.varsols = {} |
|
271 |
# set of ambiguous variables |
|
272 |
self.ambiguousvars = set() |
|
273 |
# remember if a variable has been deambiguified by another to avoid |
|
274 |
# doing the opposite |
|
275 |
self.deambification_map = {} |
|
276 |
# not invariant variables (access to final.inlined relation) |
|
277 |
self.not_invariants = set() |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1132
diff
changeset
|
278 |
|
0 | 279 |
def is_ambiguous(self, var): |
280 |
return var in self.ambiguousvars |
|
281 |
||
282 |
def restrict(self, var, restricted_domain): |
|
283 |
self.varsols[var] &= restricted_domain |
|
284 |
if var in self.ambiguousvars and self.varsols[var] == var.stinfo['possibletypes']: |
|
285 |
self.ambiguousvars.remove(var) |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1132
diff
changeset
|
286 |
|
0 | 287 |
def compute(self, rqlst): |
288 |
# set domains for each variable |
|
289 |
for varname, var in rqlst.defined_vars.iteritems(): |
|
290 |
if var.stinfo['uidrels'] or \ |
|
291 |
self.eschema(rqlst.solutions[0][varname]).is_final(): |
|
292 |
ptypes = var.stinfo['possibletypes'] |
|
293 |
else: |
|
294 |
ptypes = set(self.nfdomain) |
|
295 |
self.ambiguousvars.add(var) |
|
296 |
self.varsols[var] = ptypes |
|
297 |
if not self.ambiguousvars: |
|
298 |
return |
|
299 |
# apply relation restriction |
|
300 |
self.maydeambrels = maydeambrels = {} |
|
301 |
for rel in rqlst.iget_nodes(Relation): |
|
302 |
if rel.is_types_restriction() or rel.r_type == 'eid': |
|
303 |
continue |
|
304 |
lhs, rhs = rel.get_variable_parts() |
|
305 |
if isinstance(lhs, VariableRef) or isinstance(rhs, VariableRef): |
|
306 |
rschema = self.rschema(rel.r_type) |
|
307 |
if rschema.inlined or rschema.is_final(): |
|
308 |
self.not_invariants.add(lhs.variable) |
|
309 |
self.set_rel_constraint(lhs, rel, rschema.subjects) |
|
310 |
self.set_rel_constraint(rhs, rel, rschema.objects) |
|
311 |
# try to deambiguify more variables by considering other variables'type |
|
312 |
modified = True |
|
313 |
while modified and self.ambiguousvars: |
|
314 |
modified = False |
|
315 |
for var in self.ambiguousvars.copy(): |
|
316 |
try: |
|
317 |
for rel in (var.stinfo['relations'] & maydeambrels[var]): |
|
318 |
if self.deambiguifying_relation(var, rel): |
|
319 |
modified = True |
|
320 |
break |
|
321 |
except KeyError: |
|
322 |
# no relation to deambiguify |
|
323 |
continue |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1132
diff
changeset
|
324 |
|
0 | 325 |
def _debug_print(self): |
326 |
print 'varsols', dict((x, sorted(str(v) for v in values)) |
|
327 |
for x, values in self.varsols.iteritems()) |
|
328 |
print 'ambiguous vars', sorted(self.ambiguousvars) |
|
329 |
||
330 |
def set_rel_constraint(self, term, rel, etypes_func): |
|
331 |
if isinstance(term, VariableRef) and self.is_ambiguous(term.variable): |
|
332 |
var = term.variable |
|
333 |
if len(var.stinfo['relations'] - var.stinfo['typerels']) == 1 \ |
|
3249
280080eadb22
fix rqlannotation bug w/ identity relation in subscope
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2353
diff
changeset
|
334 |
or rel.sqlscope is var.sqlscope or rel.r_type == 'identity': |
0 | 335 |
self.restrict(var, frozenset(etypes_func())) |
336 |
try: |
|
337 |
self.maydeambrels[var].add(rel) |
|
338 |
except KeyError: |
|
339 |
self.maydeambrels[var] = set((rel,)) |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1132
diff
changeset
|
340 |
|
0 | 341 |
def deambiguifying_relation(self, var, rel): |
342 |
lhs, rhs = rel.get_variable_parts() |
|
343 |
onlhs = var is getattr(lhs, 'variable', None) |
|
344 |
other = onlhs and rhs or lhs |
|
345 |
otheretypes = None |
|
346 |
# XXX isinstance(other.variable, Variable) to skip column alias |
|
347 |
if isinstance(other, VariableRef) and isinstance(other.variable, Variable): |
|
348 |
deambiguifier = other.variable |
|
349 |
if not var is self.deambification_map.get(deambiguifier): |
|
350 |
if not var.stinfo['typerels']: |
|
351 |
otheretypes = deambiguifier.stinfo['possibletypes'] |
|
352 |
elif not self.is_ambiguous(deambiguifier): |
|
353 |
otheretypes = self.varsols[deambiguifier] |
|
354 |
elif deambiguifier in self.not_invariants: |
|
355 |
# we know variable won't be invariant, try to use |
|
356 |
# it to deambguify the current variable |
|
357 |
otheretypes = self.varsols[deambiguifier] |
|
358 |
elif isinstance(other, Constant) and other.uidtype: |
|
359 |
otheretypes = (other.uidtype,) |
|
360 |
deambiguifier = None |
|
361 |
if otheretypes is not None: |
|
967 | 362 |
# to restrict, we must check that for all type in othertypes, |
363 |
# possible types on the other end of the relation are matching |
|
364 |
# variable's possible types |
|
0 | 365 |
rschema = self.rschema(rel.r_type) |
366 |
if onlhs: |
|
367 |
rtypefunc = rschema.subjects |
|
368 |
else: |
|
369 |
rtypefunc = rschema.objects |
|
370 |
for otheretype in otheretypes: |
|
371 |
reltypes = frozenset(rtypefunc(otheretype)) |
|
372 |
if var.stinfo['possibletypes'] != reltypes: |
|
373 |
break |
|
967 | 374 |
else: |
375 |
self.restrict(var, var.stinfo['possibletypes']) |
|
0 | 376 |
self.deambification_map[var] = deambiguifier |
377 |
return True |
|
378 |
return False |