author | Sylvain Thénault <sylvain.thenault@logilab.fr> |
Tue, 21 Jul 2009 13:52:27 +0200 | |
branch | stable |
changeset 2412 | d46363eac5d7 |
parent 2101 | 08003e0354a7 |
child 2476 | 1294a6bdf3bf |
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 |
||
27 |
def empty_rset(session, rql, args, rqlst=None): |
|
28 |
"""build an empty result set object""" |
|
29 |
return ResultSet([], rql, args, rqlst=rqlst) |
|
30 |
||
31 |
def update_varmap(varmap, selected, table): |
|
32 |
"""return a sql schema to store RQL query result""" |
|
33 |
for i, term in enumerate(selected): |
|
34 |
key = term.as_string() |
|
35 |
value = '%s.C%s' % (table, i) |
|
36 |
if varmap.get(key, value) != value: |
|
37 |
raise Exception('variable name conflict on %s' % key) |
|
38 |
varmap[key] = value |
|
39 |
||
40 |
# permission utilities ######################################################## |
|
41 |
||
42 |
def var_kwargs(restriction, args): |
|
43 |
varkwargs = {} |
|
44 |
for rel in restriction.iget_nodes(Relation): |
|
45 |
cmp = rel.children[1] |
|
46 |
if rel.r_type == 'eid' and cmp.operator == '=' and \ |
|
389 | 47 |
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
|
48 |
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
|
49 |
cmp.children[0].type == 'Substitute': |
0 | 50 |
varkwargs[rel.children[0].name] = typed_eid(cmp.children[0].eval(args)) |
51 |
return varkwargs |
|
52 |
||
53 |
def check_no_password_selected(rqlst): |
|
54 |
"""check that Password entities are not selected""" |
|
55 |
for solution in rqlst.solutions: |
|
56 |
if 'Password' in solution.itervalues(): |
|
57 |
raise Unauthorized('Password selection is not allowed') |
|
58 |
||
59 |
def check_read_access(schema, user, rqlst, solution): |
|
60 |
"""check that the given user has credentials to access data read the |
|
61 |
query |
|
62 |
||
63 |
return a dict defining necessary local checks (due to use of rql expression |
|
64 |
in the schema), keys are variable names and values associated rql expression |
|
65 |
for the associated variable with the given solution |
|
66 |
""" |
|
67 |
if rqlst.where is not None: |
|
68 |
for rel in rqlst.where.iget_nodes(Relation): |
|
69 |
# XXX has_text may have specific perm ? |
|
70 |
if rel.r_type in ('is', 'is_instance_of', 'has_text', 'identity', 'eid'): |
|
71 |
continue |
|
72 |
if not schema.rschema(rel.r_type).has_access(user, 'read'): |
|
73 |
raise Unauthorized('read', rel.r_type) |
|
74 |
localchecks = {} |
|
75 |
# iterate on defined_vars and not on solutions to ignore column aliases |
|
76 |
for varname in rqlst.defined_vars: |
|
77 |
etype = solution[varname] |
|
78 |
eschema = schema.eschema(etype) |
|
79 |
if not eschema.has_access(user, 'read'): |
|
80 |
erqlexprs = eschema.get_rqlexprs('read') |
|
81 |
if not erqlexprs: |
|
82 |
ex = Unauthorized('read', etype) |
|
83 |
ex.var = varname |
|
84 |
raise ex |
|
85 |
#assert len(erqlexprs) == 1 |
|
86 |
localchecks[varname] = tuple(erqlexprs) |
|
87 |
return localchecks |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
88 |
|
0 | 89 |
def noinvariant_vars(restricted, select, nbtrees): |
90 |
# a variable can actually be invariant if it has not been restricted for |
|
91 |
# security reason or if security assertion hasn't modified the possible |
|
92 |
# solutions for the query |
|
93 |
if nbtrees != 1: |
|
94 |
for vname in restricted: |
|
95 |
try: |
|
96 |
yield select.defined_vars[vname] |
|
97 |
except KeyError: |
|
98 |
# this is an alias |
|
99 |
continue |
|
100 |
else: |
|
101 |
for vname in restricted: |
|
102 |
try: |
|
103 |
var = select.defined_vars[vname] |
|
104 |
except KeyError: |
|
105 |
# this is an alias |
|
106 |
continue |
|
107 |
if len(var.stinfo['possibletypes']) != 1: |
|
108 |
yield var |
|
109 |
||
110 |
def _expand_selection(terms, selected, aliases, select, newselect): |
|
111 |
for term in terms: |
|
112 |
for vref in term.iget_nodes(VariableRef): |
|
113 |
if not vref.name in selected: |
|
114 |
select.append_selected(vref) |
|
115 |
colalias = newselect.get_variable(vref.name, len(aliases)) |
|
116 |
aliases.append(VariableRef(colalias)) |
|
117 |
selected.add(vref.name) |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
118 |
|
0 | 119 |
# Plans ####################################################################### |
120 |
||
121 |
class ExecutionPlan(object): |
|
122 |
"""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
|
123 |
|
0 | 124 |
def __init__(self, querier, rqlst, args, session): |
125 |
# original rql syntax tree |
|
126 |
self.rqlst = rqlst |
|
127 |
self.args = args or {} |
|
128 |
# session executing the query |
|
129 |
self.session = session |
|
130 |
# quick reference to the system source |
|
131 |
self.syssource = session.pool.source('system') |
|
132 |
# execution steps |
|
133 |
self.steps = [] |
|
134 |
# index of temporary tables created during execution |
|
135 |
self.temp_tables = {} |
|
136 |
# various resource accesors |
|
137 |
self.querier = querier |
|
138 |
self.schema = querier.schema |
|
139 |
self.rqlhelper = querier._rqlhelper |
|
140 |
self.sqlannotate = querier.sqlgen_annotate |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
141 |
|
0 | 142 |
def annotate_rqlst(self): |
143 |
if not self.rqlst.annotated: |
|
144 |
self.rqlhelper.annotate(self.rqlst) |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
145 |
|
0 | 146 |
def add_step(self, step): |
147 |
"""add a step to the plan""" |
|
148 |
self.steps.append(step) |
|
149 |
||
150 |
def clean(self): |
|
151 |
"""remove temporary tables""" |
|
152 |
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
|
153 |
|
0 | 154 |
def sqlexec(self, sql, args=None): |
155 |
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
|
156 |
|
0 | 157 |
def execute(self): |
158 |
"""execute a plan and return resulting rows""" |
|
159 |
try: |
|
160 |
for step in self.steps: |
|
161 |
result = step.execute() |
|
162 |
# the latest executed step contains the full query result |
|
163 |
return result |
|
164 |
finally: |
|
165 |
self.clean() |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
166 |
|
0 | 167 |
def init_temp_table(self, table, selected, sol): |
168 |
"""initialize sql schema and variable map for a temporary table which |
|
169 |
will be used to store result for the given rqlst |
|
170 |
""" |
|
171 |
try: |
|
172 |
outputmap, sqlschema, _ = self.temp_tables[table] |
|
173 |
update_varmap(outputmap, selected, table) |
|
174 |
except KeyError: |
|
175 |
sqlschema, outputmap = self.syssource.temp_table_def(selected, sol, |
|
176 |
table) |
|
177 |
self.temp_tables[table] = [outputmap, sqlschema, False] |
|
178 |
return outputmap |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
179 |
|
0 | 180 |
def create_temp_table(self, table): |
181 |
"""create a temporary table to store result for the given rqlst""" |
|
182 |
if not self.temp_tables[table][-1]: |
|
183 |
sqlschema = self.temp_tables[table][1] |
|
184 |
self.syssource.create_temp_table(self.session, table, sqlschema) |
|
185 |
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
|
186 |
|
0 | 187 |
def preprocess(self, union, security=True): |
188 |
"""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
|
189 |
|
0 | 190 |
return rqlst to actually execute |
191 |
""" |
|
192 |
#if server.DEBUG: |
|
193 |
# print '------- preprocessing', union.as_string('utf8') |
|
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 |
|
376 |
if rtype in ('eid', 'has_text', 'is', 'is_instance_of', 'identity'): |
|
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 |
|
522 |
# application schema |
|
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 |
""" |
|
589 |
if server.DEBUG: |
|
590 |
print '*'*80 |
|
591 |
print rql |
|
592 |
# parse the query and binds variables |
|
593 |
if eid_key is not None: |
|
594 |
if not isinstance(eid_key, (tuple, list)): |
|
595 |
eid_key = (eid_key,) |
|
596 |
cachekey = [rql] |
|
597 |
for key in eid_key: |
|
598 |
try: |
|
599 |
etype = self._repo.type_from_eid(args[key], session) |
|
600 |
except KeyError: |
|
601 |
raise QueryError('bad cache key %s (no value)' % key) |
|
602 |
except TypeError: |
|
1954 | 603 |
raise QueryError('bad cache key %s (value: %r)' % ( |
604 |
key, args[key])) |
|
0 | 605 |
except UnknownEid: |
606 |
# we want queries such as "Any X WHERE X eid 9999" |
|
607 |
# return an empty result instead of raising UnknownEid |
|
608 |
return empty_rset(session, rql, args) |
|
609 |
cachekey.append(etype) |
|
610 |
cachekey = tuple(cachekey) |
|
611 |
else: |
|
612 |
cachekey = rql |
|
613 |
try: |
|
614 |
rqlst = self._rql_cache[cachekey] |
|
615 |
self.cache_hit += 1 |
|
616 |
except KeyError: |
|
617 |
self.cache_miss += 1 |
|
618 |
rqlst = self.parse(rql) |
|
619 |
try: |
|
620 |
self.solutions(session, rqlst, args) |
|
621 |
except UnknownEid: |
|
622 |
# we want queries such as "Any X WHERE X eid 9999" |
|
623 |
# return an empty result instead of raising UnknownEid |
|
624 |
return empty_rset(session, rql, args, rqlst) |
|
625 |
self._rql_cache[cachekey] = rqlst |
|
626 |
orig_rqlst = rqlst |
|
627 |
if not rqlst.TYPE == 'select': |
|
628 |
if not session.is_super_session: |
|
629 |
check_no_password_selected(rqlst) |
|
630 |
# write query, ensure session's mode is 'write' so connections |
|
631 |
# won't be released until commit/rollback |
|
632 |
session.mode = 'write' |
|
633 |
cachekey = None |
|
634 |
else: |
|
635 |
if not session.is_super_session: |
|
636 |
for select in rqlst.children: |
|
637 |
check_no_password_selected(select) |
|
638 |
# on select query, always copy the cached rqlst so we don't have to |
|
639 |
# bother modifying it. This is not necessary on write queries since |
|
640 |
# a new syntax tree is built from them. |
|
641 |
rqlst = rqlst.copy() |
|
642 |
self._rqlhelper.annotate(rqlst) |
|
643 |
# make an execution plan |
|
644 |
plan = self.plan_factory(rqlst, args, session) |
|
645 |
plan.cache_key = cachekey |
|
646 |
self._planner.build_plan(plan) |
|
647 |
# execute the plan |
|
648 |
try: |
|
649 |
results = plan.execute() |
|
650 |
except Unauthorized: |
|
651 |
# XXX this could be done in security's after_add_relation hooks |
|
652 |
# since it's actually realy only needed there (other relations |
|
653 |
# security is done *before* actual changes, and add/update entity |
|
654 |
# security is done after changes but in an operation, and exception |
|
655 |
# generated in operation's events properly generate a rollback on |
|
656 |
# the session). Even though, this is done here for a better |
|
657 |
# consistency: getting an Unauthorized exception means the |
|
658 |
# transaction has been rollbacked |
|
659 |
session.rollback() |
|
660 |
raise |
|
661 |
# build a description for the results if necessary |
|
662 |
descr = () |
|
663 |
if build_descr: |
|
664 |
if rqlst.TYPE == 'select': |
|
665 |
# sample selection |
|
666 |
descr = session.build_description(orig_rqlst, args, results) |
|
667 |
elif rqlst.TYPE == 'insert': |
|
668 |
# on insert plan, some entities may have been auto-casted, |
|
669 |
# so compute description manually even if there is only |
|
670 |
# one solution |
|
671 |
basedescr = [None] * len(plan.selected) |
|
672 |
todetermine = zip(xrange(len(plan.selected)), repeat(False)) |
|
673 |
descr = session._build_descr(results, basedescr, todetermine) |
|
674 |
# FIXME: get number of affected entities / relations on non |
|
675 |
# selection queries ? |
|
676 |
# return a result set object |
|
677 |
return ResultSet(results, rql, args, descr, eid_key, orig_rqlst) |
|
678 |
||
679 |
from logging import getLogger |
|
680 |
from cubicweb import set_log_methods |
|
681 |
LOGGER = getLogger('cubicweb.querier') |
|
682 |
set_log_methods(QuerierHelper, LOGGER) |