author | Sylvain Thénault <sylvain.thenault@logilab.fr> |
Sun, 02 Aug 2009 11:58:55 +0200 | |
changeset 2646 | d2874ddd4347 |
parent 2629 | 0d445c2171e4 |
child 2680 | 66472d85d548 |
permissions | -rw-r--r-- |
0 | 1 |
"""Helper classes to execute RQL queries on a set of sources, performing |
2 |
security checking and data aggregation. |
|
3 |
||
4 |
:organization: Logilab |
|
1977
606923dff11b
big bunch of copyright / docstring update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1954
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:
1954
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 itertools import repeat |
|
12 |
||
13 |
from logilab.common.cache import Cache |
|
14 |
from logilab.common.compat import any |
|
15 |
from rql import RQLHelper, RQLSyntaxError |
|
16 |
from rql.stmts import Union, Select |
|
1133 | 17 |
from rql.nodes import (Relation, VariableRef, Constant, SubQuery) |
0 | 18 |
|
19 |
from cubicweb import Unauthorized, QueryError, UnknownEid, typed_eid |
|
20 |
from cubicweb import server |
|
21 |
from cubicweb.rset import ResultSet |
|
22 |
||
23 |
from cubicweb.server.utils import cleanup_solutions |
|
24 |
from cubicweb.server.rqlannotation import SQLGenAnnotator, set_qdata |
|
25 |
from cubicweb.server.ssplanner import add_types_restriction |
|
26 |
||
2601
5196d213f4e3
[R querier] new READ_ONLY_RTYPES constant
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2593
diff
changeset
|
27 |
READ_ONLY_RTYPES = set(('eid', 'has_text', 'is', 'is_instance_of', 'identity')) |
5196d213f4e3
[R querier] new READ_ONLY_RTYPES constant
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2593
diff
changeset
|
28 |
|
0 | 29 |
def empty_rset(session, rql, args, rqlst=None): |
30 |
"""build an empty result set object""" |
|
31 |
return ResultSet([], rql, args, rqlst=rqlst) |
|
32 |
||
33 |
def update_varmap(varmap, selected, table): |
|
34 |
"""return a sql schema to store RQL query result""" |
|
35 |
for i, term in enumerate(selected): |
|
36 |
key = term.as_string() |
|
37 |
value = '%s.C%s' % (table, i) |
|
38 |
if varmap.get(key, value) != value: |
|
39 |
raise Exception('variable name conflict on %s' % key) |
|
40 |
varmap[key] = value |
|
41 |
||
42 |
# permission utilities ######################################################## |
|
43 |
||
44 |
def var_kwargs(restriction, args): |
|
45 |
varkwargs = {} |
|
46 |
for rel in restriction.iget_nodes(Relation): |
|
47 |
cmp = rel.children[1] |
|
48 |
if rel.r_type == 'eid' and cmp.operator == '=' and \ |
|
389 | 49 |
not rel.neged(strict=True) and \ |
321
247947250382
fix security bug w/ query using 'NOT X eid 123'
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
0
diff
changeset
|
50 |
isinstance(cmp.children[0], Constant) and \ |
247947250382
fix security bug w/ query using 'NOT X eid 123'
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
0
diff
changeset
|
51 |
cmp.children[0].type == 'Substitute': |
0 | 52 |
varkwargs[rel.children[0].name] = typed_eid(cmp.children[0].eval(args)) |
53 |
return varkwargs |
|
54 |
||
55 |
def check_no_password_selected(rqlst): |
|
56 |
"""check that Password entities are not selected""" |
|
57 |
for solution in rqlst.solutions: |
|
58 |
if 'Password' in solution.itervalues(): |
|
59 |
raise Unauthorized('Password selection is not allowed') |
|
60 |
||
61 |
def check_read_access(schema, user, rqlst, solution): |
|
62 |
"""check that the given user has credentials to access data read the |
|
63 |
query |
|
64 |
||
65 |
return a dict defining necessary local checks (due to use of rql expression |
|
66 |
in the schema), keys are variable names and values associated rql expression |
|
67 |
for the associated variable with the given solution |
|
68 |
""" |
|
69 |
if rqlst.where is not None: |
|
70 |
for rel in rqlst.where.iget_nodes(Relation): |
|
71 |
# XXX has_text may have specific perm ? |
|
2601
5196d213f4e3
[R querier] new READ_ONLY_RTYPES constant
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2593
diff
changeset
|
72 |
if rel.r_type in READ_ONLY_RTYPES: |
0 | 73 |
continue |
74 |
if not schema.rschema(rel.r_type).has_access(user, 'read'): |
|
75 |
raise Unauthorized('read', rel.r_type) |
|
76 |
localchecks = {} |
|
77 |
# iterate on defined_vars and not on solutions to ignore column aliases |
|
78 |
for varname in rqlst.defined_vars: |
|
79 |
etype = solution[varname] |
|
80 |
eschema = schema.eschema(etype) |
|
81 |
if not eschema.has_access(user, 'read'): |
|
82 |
erqlexprs = eschema.get_rqlexprs('read') |
|
83 |
if not erqlexprs: |
|
84 |
ex = Unauthorized('read', etype) |
|
85 |
ex.var = varname |
|
86 |
raise ex |
|
87 |
#assert len(erqlexprs) == 1 |
|
88 |
localchecks[varname] = tuple(erqlexprs) |
|
89 |
return localchecks |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
90 |
|
0 | 91 |
def noinvariant_vars(restricted, select, nbtrees): |
92 |
# a variable can actually be invariant if it has not been restricted for |
|
93 |
# security reason or if security assertion hasn't modified the possible |
|
94 |
# solutions for the query |
|
95 |
if nbtrees != 1: |
|
96 |
for vname in restricted: |
|
97 |
try: |
|
98 |
yield select.defined_vars[vname] |
|
99 |
except KeyError: |
|
100 |
# this is an alias |
|
101 |
continue |
|
102 |
else: |
|
103 |
for vname in restricted: |
|
104 |
try: |
|
105 |
var = select.defined_vars[vname] |
|
106 |
except KeyError: |
|
107 |
# this is an alias |
|
108 |
continue |
|
109 |
if len(var.stinfo['possibletypes']) != 1: |
|
110 |
yield var |
|
111 |
||
112 |
def _expand_selection(terms, selected, aliases, select, newselect): |
|
113 |
for term in terms: |
|
114 |
for vref in term.iget_nodes(VariableRef): |
|
115 |
if not vref.name in selected: |
|
116 |
select.append_selected(vref) |
|
117 |
colalias = newselect.get_variable(vref.name, len(aliases)) |
|
118 |
aliases.append(VariableRef(colalias)) |
|
119 |
selected.add(vref.name) |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
120 |
|
0 | 121 |
# Plans ####################################################################### |
122 |
||
123 |
class ExecutionPlan(object): |
|
124 |
"""the execution model of a rql query, composed of querier steps""" |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
125 |
|
0 | 126 |
def __init__(self, querier, rqlst, args, session): |
127 |
# original rql syntax tree |
|
128 |
self.rqlst = rqlst |
|
129 |
self.args = args or {} |
|
130 |
# session executing the query |
|
131 |
self.session = session |
|
132 |
# quick reference to the system source |
|
133 |
self.syssource = session.pool.source('system') |
|
134 |
# execution steps |
|
135 |
self.steps = [] |
|
136 |
# index of temporary tables created during execution |
|
137 |
self.temp_tables = {} |
|
138 |
# various resource accesors |
|
139 |
self.querier = querier |
|
140 |
self.schema = querier.schema |
|
141 |
self.rqlhelper = querier._rqlhelper |
|
142 |
self.sqlannotate = querier.sqlgen_annotate |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
143 |
|
0 | 144 |
def annotate_rqlst(self): |
145 |
if not self.rqlst.annotated: |
|
146 |
self.rqlhelper.annotate(self.rqlst) |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
147 |
|
0 | 148 |
def add_step(self, step): |
149 |
"""add a step to the plan""" |
|
150 |
self.steps.append(step) |
|
151 |
||
152 |
def clean(self): |
|
153 |
"""remove temporary tables""" |
|
154 |
self.syssource.clean_temp_data(self.session, self.temp_tables) |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
155 |
|
0 | 156 |
def sqlexec(self, sql, args=None): |
157 |
return self.syssource.sqlexec(self.session, sql, args) |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
158 |
|
0 | 159 |
def execute(self): |
160 |
"""execute a plan and return resulting rows""" |
|
161 |
try: |
|
162 |
for step in self.steps: |
|
163 |
result = step.execute() |
|
164 |
# the latest executed step contains the full query result |
|
165 |
return result |
|
166 |
finally: |
|
167 |
self.clean() |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
168 |
|
0 | 169 |
def init_temp_table(self, table, selected, sol): |
170 |
"""initialize sql schema and variable map for a temporary table which |
|
171 |
will be used to store result for the given rqlst |
|
172 |
""" |
|
173 |
try: |
|
174 |
outputmap, sqlschema, _ = self.temp_tables[table] |
|
175 |
update_varmap(outputmap, selected, table) |
|
176 |
except KeyError: |
|
177 |
sqlschema, outputmap = self.syssource.temp_table_def(selected, sol, |
|
178 |
table) |
|
179 |
self.temp_tables[table] = [outputmap, sqlschema, False] |
|
180 |
return outputmap |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
181 |
|
0 | 182 |
def create_temp_table(self, table): |
183 |
"""create a temporary table to store result for the given rqlst""" |
|
184 |
if not self.temp_tables[table][-1]: |
|
185 |
sqlschema = self.temp_tables[table][1] |
|
186 |
self.syssource.create_temp_table(self.session, table, sqlschema) |
|
187 |
self.temp_tables[table][-1] = True |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
188 |
|
0 | 189 |
def preprocess(self, union, security=True): |
190 |
"""insert security when necessary then annotate rql st for sql generation |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
191 |
|
0 | 192 |
return rqlst to actually execute |
193 |
""" |
|
194 |
noinvariant = set() |
|
195 |
if security and not self.session.is_super_session: |
|
196 |
self._insert_security(union, noinvariant) |
|
197 |
self.rqlhelper.simplify(union) |
|
198 |
self.sqlannotate(union) |
|
438 | 199 |
set_qdata(self.schema.rschema, union, noinvariant) |
0 | 200 |
if union.has_text_query: |
201 |
self.cache_key = None |
|
202 |
||
203 |
def _insert_security(self, union, noinvariant): |
|
204 |
rh = self.rqlhelper |
|
205 |
for select in union.children[:]: |
|
206 |
for subquery in select.with_: |
|
207 |
self._insert_security(subquery.query, noinvariant) |
|
208 |
localchecks, restricted = self._check_permissions(select) |
|
209 |
if any(localchecks): |
|
210 |
rewrite = self.session.rql_rewriter.rewrite |
|
211 |
nbtrees = len(localchecks) |
|
212 |
myunion = union |
|
213 |
# transform in subquery when len(localchecks)>1 and groups |
|
214 |
if nbtrees > 1 and (select.orderby or select.groupby or |
|
215 |
select.having or select.has_aggregat or |
|
216 |
select.limit or select.offset): |
|
217 |
newselect = Select() |
|
218 |
# only select variables in subqueries |
|
219 |
origselection = select.selection |
|
220 |
select.select_only_variables() |
|
221 |
select.has_aggregat = False |
|
222 |
# create subquery first so correct node are used on copy |
|
223 |
# (eg ColumnAlias instead of Variable) |
|
224 |
aliases = [VariableRef(newselect.get_variable(vref.name, i)) |
|
225 |
for i, vref in enumerate(select.selection)] |
|
226 |
selected = set(vref.name for vref in aliases) |
|
227 |
# now copy original selection and groups |
|
228 |
for term in origselection: |
|
229 |
newselect.append_selected(term.copy(newselect)) |
|
230 |
if select.orderby: |
|
231 |
newselect.set_orderby([s.copy(newselect) for s in select.orderby]) |
|
232 |
_expand_selection(select.orderby, selected, aliases, select, newselect) |
|
233 |
select.orderby = () # XXX dereference? |
|
234 |
if select.groupby: |
|
235 |
newselect.set_groupby([g.copy(newselect) for g in select.groupby]) |
|
236 |
_expand_selection(select.groupby, selected, aliases, select, newselect) |
|
237 |
select.groupby = () # XXX dereference? |
|
238 |
if select.having: |
|
239 |
newselect.set_having([g.copy(newselect) for g in select.having]) |
|
240 |
_expand_selection(select.having, selected, aliases, select, newselect) |
|
241 |
select.having = () # XXX dereference? |
|
242 |
if select.limit: |
|
243 |
newselect.limit = select.limit |
|
244 |
select.limit = None |
|
245 |
if select.offset: |
|
246 |
newselect.offset = select.offset |
|
247 |
select.offset = 0 |
|
248 |
myunion = Union() |
|
249 |
newselect.set_with([SubQuery(aliases, myunion)], check=False) |
|
250 |
solutions = [sol.copy() for sol in select.solutions] |
|
251 |
cleanup_solutions(newselect, solutions) |
|
252 |
newselect.set_possible_types(solutions) |
|
253 |
# if some solutions doesn't need rewriting, insert original |
|
254 |
# select as first union subquery |
|
255 |
if () in localchecks: |
|
256 |
myunion.append(select) |
|
257 |
# we're done, replace original select by the new select with |
|
258 |
# subqueries (more added in the loop below) |
|
259 |
union.replace(select, newselect) |
|
260 |
elif not () in localchecks: |
|
261 |
union.remove(select) |
|
262 |
for lcheckdef, lchecksolutions in localchecks.iteritems(): |
|
263 |
if not lcheckdef: |
|
264 |
continue |
|
265 |
myrqlst = select.copy(solutions=lchecksolutions) |
|
266 |
myunion.append(myrqlst) |
|
267 |
# in-place rewrite + annotation / simplification |
|
268 |
rewrite(myrqlst, lcheckdef, lchecksolutions, self.args) |
|
269 |
noinvariant.update(noinvariant_vars(restricted, myrqlst, nbtrees)) |
|
270 |
if () in localchecks: |
|
271 |
select.set_possible_types(localchecks[()]) |
|
272 |
add_types_restriction(self.schema, select) |
|
273 |
noinvariant.update(noinvariant_vars(restricted, select, nbtrees)) |
|
274 |
||
275 |
def _check_permissions(self, rqlst): |
|
276 |
"""return a dict defining "local checks", e.g. RQLExpression defined in |
|
277 |
the schema that should be inserted in the original query |
|
278 |
||
279 |
solutions where a variable has a type which the user can't definitly read |
|
280 |
are removed, else if the user may read it (eg if an rql expression is |
|
281 |
defined for the "read" permission of the related type), the local checks |
|
282 |
dict for the solution is updated |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
283 |
|
0 | 284 |
return a dict with entries for each different local check necessary, |
285 |
with associated solutions as value. A local check is defined by a list |
|
286 |
of 2-uple, with variable name as first item and the necessary rql |
|
287 |
expression as second item for each variable which has to be checked. |
|
288 |
So solutions which don't require local checks will be associated to |
|
289 |
the empty tuple key. |
|
290 |
||
291 |
note: rqlst should not have been simplified at this point |
|
292 |
""" |
|
293 |
assert not self.session.is_super_session |
|
294 |
user = self.session.user |
|
295 |
schema = self.schema |
|
296 |
msgs = [] |
|
297 |
# dictionnary of variables restricted for security reason |
|
298 |
localchecks = {} |
|
299 |
if rqlst.where is not None: |
|
300 |
varkwargs = var_kwargs(rqlst.where, self.args) |
|
2101
08003e0354a7
update transaction data api
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
301 |
neweids = self.session.transaction_data.get('neweids', ()) |
0 | 302 |
else: |
303 |
varkwargs = None |
|
304 |
restricted_vars = set() |
|
305 |
newsolutions = [] |
|
306 |
for solution in rqlst.solutions: |
|
307 |
try: |
|
308 |
localcheck = check_read_access(schema, user, rqlst, solution) |
|
309 |
except Unauthorized, ex: |
|
310 |
msg = 'remove %s from solutions since %s has no %s access to %s' |
|
311 |
msg %= (solution, user.login, ex.args[0], ex.args[1]) |
|
312 |
msgs.append(msg) |
|
313 |
LOGGER.info(msg) |
|
314 |
else: |
|
315 |
newsolutions.append(solution) |
|
316 |
if varkwargs: |
|
317 |
# try to benefit of rqlexpr.check cache for entities which |
|
318 |
# are specified by eid in query'args |
|
319 |
for varname, eid in varkwargs.iteritems(): |
|
320 |
try: |
|
321 |
rqlexprs = localcheck.pop(varname) |
|
322 |
except KeyError: |
|
323 |
continue |
|
324 |
if eid in neweids: |
|
325 |
continue |
|
326 |
for rqlexpr in rqlexprs: |
|
327 |
if rqlexpr.check(self.session, eid): |
|
328 |
break |
|
329 |
else: |
|
330 |
raise Unauthorized() |
|
331 |
restricted_vars.update(localcheck) |
|
332 |
localchecks.setdefault(tuple(localcheck.iteritems()), []).append(solution) |
|
333 |
# raise Unautorized exception if the user can't access to any solution |
|
334 |
if not newsolutions: |
|
335 |
raise Unauthorized('\n'.join(msgs)) |
|
336 |
rqlst.set_possible_types(newsolutions) |
|
337 |
return localchecks, restricted_vars |
|
338 |
||
339 |
def finalize(self, select, solutions, insertedvars): |
|
340 |
rqlst = Union() |
|
341 |
rqlst.append(select) |
|
342 |
for mainvarname, rschema, newvarname in insertedvars: |
|
343 |
nvartype = str(rschema.objects(solutions[0][mainvarname])[0]) |
|
344 |
for sol in solutions: |
|
345 |
sol[newvarname] = nvartype |
|
346 |
select.clean_solutions(solutions) |
|
347 |
self.rqlhelper.annotate(rqlst) |
|
348 |
self.preprocess(rqlst, security=False) |
|
349 |
return rqlst |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
350 |
|
0 | 351 |
class InsertPlan(ExecutionPlan): |
352 |
"""an execution model specific to the INSERT rql query |
|
353 |
""" |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
354 |
|
0 | 355 |
def __init__(self, querier, rqlst, args, session): |
356 |
ExecutionPlan.__init__(self, querier, rqlst, args, session) |
|
357 |
# save originaly selected variable, we may modify this |
|
358 |
# dictionary for substitution (query parameters) |
|
359 |
self.selected = rqlst.selection |
|
360 |
# list of new or updated entities definition (utils.Entity) |
|
361 |
self.e_defs = [[]] |
|
362 |
# list of new relation definition (3-uple (from_eid, r_type, to_eid) |
|
363 |
self.r_defs = [] |
|
364 |
# indexes to track entity definitions bound to relation definitions |
|
365 |
self._r_subj_index = {} |
|
366 |
self._r_obj_index = {} |
|
367 |
self._expanded_r_defs = {} |
|
368 |
||
369 |
def relation_definitions(self, rqlst, to_build): |
|
370 |
"""add constant values to entity def, mark variables to be selected |
|
371 |
""" |
|
372 |
to_select = {} |
|
373 |
for relation in rqlst.main_relations: |
|
374 |
lhs, rhs = relation.get_variable_parts() |
|
375 |
rtype = relation.r_type |
|
2601
5196d213f4e3
[R querier] new READ_ONLY_RTYPES constant
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2593
diff
changeset
|
376 |
if rtype in READ_ONLY_RTYPES: |
0 | 377 |
raise QueryError("can't assign to %s" % rtype) |
378 |
try: |
|
379 |
edef = to_build[str(lhs)] |
|
380 |
except KeyError: |
|
381 |
# lhs var is not to build, should be selected and added as an |
|
382 |
# object relation |
|
383 |
edef = to_build[str(rhs)] |
|
384 |
to_select.setdefault(edef, []).append((rtype, lhs, 1)) |
|
385 |
else: |
|
386 |
if isinstance(rhs, Constant) and not rhs.uid: |
|
387 |
# add constant values to entity def |
|
388 |
value = rhs.eval(self.args) |
|
389 |
eschema = edef.e_schema |
|
390 |
attrtype = eschema.subject_relation(rtype).objects(eschema)[0] |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
391 |
if attrtype == 'Password' and isinstance(value, unicode): |
0 | 392 |
value = value.encode('UTF8') |
393 |
edef[rtype] = value |
|
394 |
elif to_build.has_key(str(rhs)): |
|
395 |
# create a relation between two newly created variables |
|
396 |
self.add_relation_def((edef, rtype, to_build[rhs.name])) |
|
397 |
else: |
|
398 |
to_select.setdefault(edef, []).append( (rtype, rhs, 0) ) |
|
399 |
return to_select |
|
400 |
||
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
401 |
|
0 | 402 |
def add_entity_def(self, edef): |
403 |
"""add an entity definition to build""" |
|
404 |
edef.querier_pending_relations = {} |
|
405 |
self.e_defs[-1].append(edef) |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
406 |
|
0 | 407 |
def add_relation_def(self, rdef): |
408 |
"""add an relation definition to build""" |
|
409 |
self.r_defs.append(rdef) |
|
410 |
if not isinstance(rdef[0], int): |
|
411 |
self._r_subj_index.setdefault(rdef[0], []).append(rdef) |
|
412 |
if not isinstance(rdef[2], int): |
|
413 |
self._r_obj_index.setdefault(rdef[2], []).append(rdef) |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
414 |
|
0 | 415 |
def substitute_entity_def(self, edef, edefs): |
416 |
"""substitute an incomplete entity definition by a list of complete |
|
417 |
equivalents |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
418 |
|
0 | 419 |
e.g. on queries such as :: |
420 |
INSERT Personne X, Societe Y: X nom N, Y nom 'toto', X travaille Y |
|
421 |
WHERE U login 'admin', U login N |
|
422 |
||
423 |
X will be inserted as many times as U exists, and so the X travaille Y |
|
424 |
relations as to be added as many time as X is inserted |
|
425 |
""" |
|
426 |
if not edefs or not self.e_defs: |
|
427 |
# no result, no entity will be created |
|
428 |
self.e_defs = () |
|
429 |
return |
|
430 |
# first remove the incomplete entity definition |
|
431 |
colidx = self.e_defs[0].index(edef) |
|
432 |
for i, row in enumerate(self.e_defs[:]): |
|
433 |
self.e_defs[i][colidx] = edefs[0] |
|
434 |
samplerow = self.e_defs[i] |
|
435 |
for edef in edefs[1:]: |
|
436 |
row = samplerow[:] |
|
437 |
row[colidx] = edef |
|
438 |
self.e_defs.append(row) |
|
439 |
# now, see if this entity def is referenced as subject in some relation |
|
440 |
# definition |
|
441 |
if self._r_subj_index.has_key(edef): |
|
442 |
for rdef in self._r_subj_index[edef]: |
|
443 |
expanded = self._expanded(rdef) |
|
444 |
result = [] |
|
445 |
for exp_rdef in expanded: |
|
446 |
for edef in edefs: |
|
447 |
result.append( (edef, exp_rdef[1], exp_rdef[2]) ) |
|
448 |
self._expanded_r_defs[rdef] = result |
|
449 |
# and finally, see if this entity def is referenced as object in some |
|
450 |
# relation definition |
|
451 |
if self._r_obj_index.has_key(edef): |
|
452 |
for rdef in self._r_obj_index[edef]: |
|
453 |
expanded = self._expanded(rdef) |
|
454 |
result = [] |
|
455 |
for exp_rdef in expanded: |
|
456 |
for edef in edefs: |
|
457 |
result.append( (exp_rdef[0], exp_rdef[1], edef) ) |
|
458 |
self._expanded_r_defs[rdef] = result |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
459 |
|
0 | 460 |
def _expanded(self, rdef): |
461 |
"""return expanded value for the given relation definition""" |
|
462 |
try: |
|
463 |
return self._expanded_r_defs[rdef] |
|
464 |
except KeyError: |
|
465 |
self.r_defs.remove(rdef) |
|
466 |
return [rdef] |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
467 |
|
0 | 468 |
def relation_defs(self): |
469 |
"""return the list for relation definitions to insert""" |
|
470 |
for rdefs in self._expanded_r_defs.values(): |
|
471 |
for rdef in rdefs: |
|
472 |
yield rdef |
|
473 |
for rdef in self.r_defs: |
|
474 |
yield rdef |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
475 |
|
0 | 476 |
def insert_entity_defs(self): |
477 |
"""return eids of inserted entities in a suitable form for the resulting |
|
478 |
result set, e.g.: |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
479 |
|
0 | 480 |
e.g. on queries such as :: |
481 |
INSERT Personne X, Societe Y: X nom N, Y nom 'toto', X travaille Y |
|
482 |
WHERE U login 'admin', U login N |
|
483 |
||
484 |
if there is two entities matching U, the result set will look like |
|
485 |
[(eidX1, eidY1), (eidX2, eidY2)] |
|
486 |
""" |
|
487 |
session = self.session |
|
488 |
repo = session.repo |
|
489 |
results = [] |
|
490 |
for row in self.e_defs: |
|
491 |
results.append([repo.glob_add_entity(session, edef) |
|
492 |
for edef in row]) |
|
493 |
return results |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
494 |
|
0 | 495 |
def insert_relation_defs(self): |
496 |
session = self.session |
|
497 |
repo = session.repo |
|
498 |
for subj, rtype, obj in self.relation_defs(): |
|
499 |
# if a string is given into args instead of an int, we get it here |
|
500 |
if isinstance(subj, basestring): |
|
501 |
subj = typed_eid(subj) |
|
502 |
elif not isinstance(subj, (int, long)): |
|
503 |
subj = subj.eid |
|
504 |
if isinstance(obj, basestring): |
|
505 |
obj = typed_eid(obj) |
|
506 |
elif not isinstance(obj, (int, long)): |
|
507 |
obj = obj.eid |
|
508 |
if repo.schema.rschema(rtype).inlined: |
|
509 |
entity = session.eid_rset(subj).get_entity(0, 0) |
|
510 |
entity[rtype] = obj |
|
511 |
repo.glob_update_entity(session, entity) |
|
512 |
else: |
|
513 |
repo.glob_add_relation(session, subj, rtype, obj) |
|
514 |
||
515 |
||
516 |
class QuerierHelper(object): |
|
517 |
"""helper class to execute rql queries, putting all things together""" |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
518 |
|
0 | 519 |
def __init__(self, repo, schema): |
520 |
# system info helper |
|
521 |
self._repo = repo |
|
2476
1294a6bdf3bf
application -> instance where it makes sense
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2101
diff
changeset
|
522 |
# instance schema |
0 | 523 |
self.set_schema(schema) |
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
524 |
|
0 | 525 |
def set_schema(self, schema): |
526 |
self.schema = schema |
|
527 |
# rql parsing / analysing helper |
|
528 |
self._rqlhelper = RQLHelper(schema, special_relations={'eid': 'uid', |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
529 |
'has_text': 'fti'}) |
0 | 530 |
self._rql_cache = Cache(self._repo.config['rql-cache-size']) |
531 |
self.cache_hit, self.cache_miss = 0, 0 |
|
532 |
# rql planner |
|
533 |
# note: don't use repo.sources, may not be built yet, and also "admin" |
|
534 |
# isn't an actual source |
|
535 |
if len([uri for uri in self._repo.config.sources() if uri != 'admin']) < 2: |
|
536 |
from cubicweb.server.ssplanner import SSPlanner |
|
537 |
self._planner = SSPlanner(schema, self._rqlhelper) |
|
538 |
else: |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
539 |
from cubicweb.server.msplanner import MSPlanner |
0 | 540 |
self._planner = MSPlanner(schema, self._rqlhelper) |
541 |
# sql generation annotator |
|
542 |
self.sqlgen_annotate = SQLGenAnnotator(schema).annotate |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
543 |
|
0 | 544 |
def parse(self, rql, annotate=False): |
545 |
"""return a rql syntax tree for the given rql""" |
|
546 |
try: |
|
547 |
return self._rqlhelper.parse(unicode(rql), annotate=annotate) |
|
548 |
except UnicodeError: |
|
549 |
raise RQLSyntaxError(rql) |
|
550 |
||
551 |
def solutions(self, session, rqlst, args): |
|
552 |
assert session is not None |
|
553 |
def type_from_eid(eid, type_from_eid=self._repo.type_from_eid, |
|
554 |
session=session): |
|
555 |
return type_from_eid(eid, session) |
|
556 |
self._rqlhelper.compute_solutions(rqlst, {'eid': type_from_eid}, args) |
|
557 |
||
558 |
def plan_factory(self, rqlst, args, session): |
|
559 |
"""create an execution plan for an INSERT RQL query""" |
|
560 |
if rqlst.TYPE == 'insert': |
|
561 |
return InsertPlan(self, rqlst, args, session) |
|
562 |
return ExecutionPlan(self, rqlst, args, session) |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
563 |
|
0 | 564 |
def execute(self, session, rql, args=None, eid_key=None, build_descr=True): |
565 |
"""execute a rql query, return resulting rows and their description in |
|
566 |
a `ResultSet` object |
|
567 |
||
568 |
* `rql` should be an unicode string or a plain ascii string |
|
569 |
* `args` the optional parameters dictionary associated to the query |
|
570 |
* `build_descr` is a boolean flag indicating if the description should |
|
571 |
be built on select queries (if false, the description will be en empty |
|
572 |
list) |
|
573 |
* `eid_key` must be both a key in args and a substitution in the rql |
|
574 |
query. It should be used to enhance cacheability of rql queries. |
|
575 |
It may be a tuple for keys in args. |
|
576 |
eid_key must be providen in case where a eid substitution is providen |
|
577 |
and resolve some ambiguity in the possible solutions infered for each |
|
578 |
variable in the query. |
|
579 |
||
580 |
on INSERT queries, there will be on row with the eid of each inserted |
|
581 |
entity |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
582 |
|
0 | 583 |
result for DELETE and SET queries is undefined yet |
584 |
||
585 |
to maximize the rql parsing/analyzing cache performance, you should |
|
586 |
always use substitute arguments in queries (eg avoid query such as |
|
587 |
'Any X WHERE X eid 123'!) |
|
588 |
""" |
|
2621
1b9d08840a0e
R [querier] debugging tweaks
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2601
diff
changeset
|
589 |
if server.DEBUG & (server.DBG_RQL | server.DBG_SQL): |
2629
0d445c2171e4
R [querier] debugging tweaks
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2621
diff
changeset
|
590 |
if server.DEBUG & (server.DBG_MORE | server.DBG_SQL): |
2621
1b9d08840a0e
R [querier] debugging tweaks
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2601
diff
changeset
|
591 |
print '*'*80 |
2646
d2874ddd4347
#F [querier] debugging tweak
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2629
diff
changeset
|
592 |
print 'querier input', rql, args |
0 | 593 |
# parse the query and binds variables |
594 |
if eid_key is not None: |
|
595 |
if not isinstance(eid_key, (tuple, list)): |
|
596 |
eid_key = (eid_key,) |
|
597 |
cachekey = [rql] |
|
598 |
for key in eid_key: |
|
599 |
try: |
|
600 |
etype = self._repo.type_from_eid(args[key], session) |
|
601 |
except KeyError: |
|
602 |
raise QueryError('bad cache key %s (no value)' % key) |
|
603 |
except TypeError: |
|
1954 | 604 |
raise QueryError('bad cache key %s (value: %r)' % ( |
605 |
key, args[key])) |
|
0 | 606 |
except UnknownEid: |
607 |
# we want queries such as "Any X WHERE X eid 9999" |
|
608 |
# return an empty result instead of raising UnknownEid |
|
609 |
return empty_rset(session, rql, args) |
|
610 |
cachekey.append(etype) |
|
611 |
cachekey = tuple(cachekey) |
|
612 |
else: |
|
613 |
cachekey = rql |
|
614 |
try: |
|
615 |
rqlst = self._rql_cache[cachekey] |
|
616 |
self.cache_hit += 1 |
|
617 |
except KeyError: |
|
618 |
self.cache_miss += 1 |
|
619 |
rqlst = self.parse(rql) |
|
620 |
try: |
|
621 |
self.solutions(session, rqlst, args) |
|
622 |
except UnknownEid: |
|
623 |
# we want queries such as "Any X WHERE X eid 9999" |
|
624 |
# return an empty result instead of raising UnknownEid |
|
625 |
return empty_rset(session, rql, args, rqlst) |
|
626 |
self._rql_cache[cachekey] = rqlst |
|
627 |
orig_rqlst = rqlst |
|
628 |
if not rqlst.TYPE == 'select': |
|
629 |
if not session.is_super_session: |
|
630 |
check_no_password_selected(rqlst) |
|
631 |
# write query, ensure session's mode is 'write' so connections |
|
632 |
# won't be released until commit/rollback |
|
633 |
session.mode = 'write' |
|
634 |
cachekey = None |
|
635 |
else: |
|
636 |
if not session.is_super_session: |
|
637 |
for select in rqlst.children: |
|
638 |
check_no_password_selected(select) |
|
639 |
# on select query, always copy the cached rqlst so we don't have to |
|
640 |
# bother modifying it. This is not necessary on write queries since |
|
641 |
# a new syntax tree is built from them. |
|
642 |
rqlst = rqlst.copy() |
|
643 |
self._rqlhelper.annotate(rqlst) |
|
644 |
# make an execution plan |
|
645 |
plan = self.plan_factory(rqlst, args, session) |
|
646 |
plan.cache_key = cachekey |
|
647 |
self._planner.build_plan(plan) |
|
648 |
# execute the plan |
|
649 |
try: |
|
650 |
results = plan.execute() |
|
651 |
except Unauthorized: |
|
652 |
# XXX this could be done in security's after_add_relation hooks |
|
653 |
# since it's actually realy only needed there (other relations |
|
654 |
# security is done *before* actual changes, and add/update entity |
|
655 |
# security is done after changes but in an operation, and exception |
|
656 |
# generated in operation's events properly generate a rollback on |
|
657 |
# the session). Even though, this is done here for a better |
|
658 |
# consistency: getting an Unauthorized exception means the |
|
659 |
# transaction has been rollbacked |
|
660 |
session.rollback() |
|
661 |
raise |
|
662 |
# build a description for the results if necessary |
|
663 |
descr = () |
|
664 |
if build_descr: |
|
665 |
if rqlst.TYPE == 'select': |
|
666 |
# sample selection |
|
667 |
descr = session.build_description(orig_rqlst, args, results) |
|
668 |
elif rqlst.TYPE == 'insert': |
|
669 |
# on insert plan, some entities may have been auto-casted, |
|
670 |
# so compute description manually even if there is only |
|
671 |
# one solution |
|
672 |
basedescr = [None] * len(plan.selected) |
|
673 |
todetermine = zip(xrange(len(plan.selected)), repeat(False)) |
|
674 |
descr = session._build_descr(results, basedescr, todetermine) |
|
675 |
# FIXME: get number of affected entities / relations on non |
|
676 |
# selection queries ? |
|
677 |
# return a result set object |
|
678 |
return ResultSet(results, rql, args, descr, eid_key, orig_rqlst) |
|
679 |
||
680 |
from logging import getLogger |
|
681 |
from cubicweb import set_log_methods |
|
682 |
LOGGER = getLogger('cubicweb.querier') |
|
683 |
set_log_methods(QuerierHelper, LOGGER) |