author | Alexandre Fayolle <alexandre.fayolle@logilab.fr> |
Fri, 09 Oct 2009 15:53:02 +0200 | |
branch | stable |
changeset 3626 | 017869a514c3 |
parent 3240 | 8604a15995d1 |
child 3689 | deb13e88e037 |
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.sqlannotate = querier.sqlgen_annotate |
|
3240
8604a15995d1
refactor so that rql rewriter may be used outside the server. Enhance it to be usable for RRQLExpression as well
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3171
diff
changeset
|
142 |
self.rqlhelper = session.vreg.rqlhelper |
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 |
|
3240
8604a15995d1
refactor so that rql rewriter may be used outside the server. Enhance it to be usable for RRQLExpression as well
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3171
diff
changeset
|
268 |
lcheckdef = [((varmap, 'X'), rqlexprs) |
8604a15995d1
refactor so that rql rewriter may be used outside the server. Enhance it to be usable for RRQLExpression as well
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3171
diff
changeset
|
269 |
for varmap, rqlexprs in lcheckdef] |
0 | 270 |
rewrite(myrqlst, lcheckdef, lchecksolutions, self.args) |
271 |
noinvariant.update(noinvariant_vars(restricted, myrqlst, nbtrees)) |
|
272 |
if () in localchecks: |
|
273 |
select.set_possible_types(localchecks[()]) |
|
274 |
add_types_restriction(self.schema, select) |
|
275 |
noinvariant.update(noinvariant_vars(restricted, select, nbtrees)) |
|
276 |
||
277 |
def _check_permissions(self, rqlst): |
|
278 |
"""return a dict defining "local checks", e.g. RQLExpression defined in |
|
279 |
the schema that should be inserted in the original query |
|
280 |
||
281 |
solutions where a variable has a type which the user can't definitly read |
|
282 |
are removed, else if the user may read it (eg if an rql expression is |
|
283 |
defined for the "read" permission of the related type), the local checks |
|
284 |
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
|
285 |
|
0 | 286 |
return a dict with entries for each different local check necessary, |
287 |
with associated solutions as value. A local check is defined by a list |
|
288 |
of 2-uple, with variable name as first item and the necessary rql |
|
289 |
expression as second item for each variable which has to be checked. |
|
290 |
So solutions which don't require local checks will be associated to |
|
291 |
the empty tuple key. |
|
292 |
||
293 |
note: rqlst should not have been simplified at this point |
|
294 |
""" |
|
295 |
assert not self.session.is_super_session |
|
296 |
user = self.session.user |
|
297 |
schema = self.schema |
|
298 |
msgs = [] |
|
299 |
# dictionnary of variables restricted for security reason |
|
300 |
localchecks = {} |
|
301 |
if rqlst.where is not None: |
|
302 |
varkwargs = var_kwargs(rqlst.where, self.args) |
|
2101
08003e0354a7
update transaction data api
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
303 |
neweids = self.session.transaction_data.get('neweids', ()) |
0 | 304 |
else: |
305 |
varkwargs = None |
|
306 |
restricted_vars = set() |
|
307 |
newsolutions = [] |
|
308 |
for solution in rqlst.solutions: |
|
309 |
try: |
|
310 |
localcheck = check_read_access(schema, user, rqlst, solution) |
|
311 |
except Unauthorized, ex: |
|
312 |
msg = 'remove %s from solutions since %s has no %s access to %s' |
|
313 |
msg %= (solution, user.login, ex.args[0], ex.args[1]) |
|
314 |
msgs.append(msg) |
|
315 |
LOGGER.info(msg) |
|
316 |
else: |
|
317 |
newsolutions.append(solution) |
|
318 |
if varkwargs: |
|
319 |
# try to benefit of rqlexpr.check cache for entities which |
|
320 |
# are specified by eid in query'args |
|
321 |
for varname, eid in varkwargs.iteritems(): |
|
322 |
try: |
|
323 |
rqlexprs = localcheck.pop(varname) |
|
324 |
except KeyError: |
|
325 |
continue |
|
326 |
if eid in neweids: |
|
327 |
continue |
|
328 |
for rqlexpr in rqlexprs: |
|
329 |
if rqlexpr.check(self.session, eid): |
|
330 |
break |
|
331 |
else: |
|
332 |
raise Unauthorized() |
|
333 |
restricted_vars.update(localcheck) |
|
334 |
localchecks.setdefault(tuple(localcheck.iteritems()), []).append(solution) |
|
335 |
# raise Unautorized exception if the user can't access to any solution |
|
336 |
if not newsolutions: |
|
337 |
raise Unauthorized('\n'.join(msgs)) |
|
338 |
rqlst.set_possible_types(newsolutions) |
|
339 |
return localchecks, restricted_vars |
|
340 |
||
341 |
def finalize(self, select, solutions, insertedvars): |
|
342 |
rqlst = Union() |
|
343 |
rqlst.append(select) |
|
344 |
for mainvarname, rschema, newvarname in insertedvars: |
|
345 |
nvartype = str(rschema.objects(solutions[0][mainvarname])[0]) |
|
346 |
for sol in solutions: |
|
347 |
sol[newvarname] = nvartype |
|
348 |
select.clean_solutions(solutions) |
|
349 |
self.rqlhelper.annotate(rqlst) |
|
350 |
self.preprocess(rqlst, security=False) |
|
351 |
return rqlst |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
352 |
|
0 | 353 |
class InsertPlan(ExecutionPlan): |
354 |
"""an execution model specific to the INSERT rql query |
|
355 |
""" |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
356 |
|
0 | 357 |
def __init__(self, querier, rqlst, args, session): |
358 |
ExecutionPlan.__init__(self, querier, rqlst, args, session) |
|
359 |
# save originaly selected variable, we may modify this |
|
360 |
# dictionary for substitution (query parameters) |
|
361 |
self.selected = rqlst.selection |
|
362 |
# list of new or updated entities definition (utils.Entity) |
|
363 |
self.e_defs = [[]] |
|
364 |
# list of new relation definition (3-uple (from_eid, r_type, to_eid) |
|
365 |
self.r_defs = [] |
|
366 |
# indexes to track entity definitions bound to relation definitions |
|
367 |
self._r_subj_index = {} |
|
368 |
self._r_obj_index = {} |
|
369 |
self._expanded_r_defs = {} |
|
370 |
||
371 |
def relation_definitions(self, rqlst, to_build): |
|
372 |
"""add constant values to entity def, mark variables to be selected |
|
373 |
""" |
|
374 |
to_select = {} |
|
375 |
for relation in rqlst.main_relations: |
|
376 |
lhs, rhs = relation.get_variable_parts() |
|
377 |
rtype = relation.r_type |
|
2601
5196d213f4e3
[R querier] new READ_ONLY_RTYPES constant
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2593
diff
changeset
|
378 |
if rtype in READ_ONLY_RTYPES: |
0 | 379 |
raise QueryError("can't assign to %s" % rtype) |
380 |
try: |
|
381 |
edef = to_build[str(lhs)] |
|
382 |
except KeyError: |
|
383 |
# lhs var is not to build, should be selected and added as an |
|
384 |
# object relation |
|
385 |
edef = to_build[str(rhs)] |
|
386 |
to_select.setdefault(edef, []).append((rtype, lhs, 1)) |
|
387 |
else: |
|
388 |
if isinstance(rhs, Constant) and not rhs.uid: |
|
389 |
# add constant values to entity def |
|
390 |
value = rhs.eval(self.args) |
|
391 |
eschema = edef.e_schema |
|
392 |
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
|
393 |
if attrtype == 'Password' and isinstance(value, unicode): |
0 | 394 |
value = value.encode('UTF8') |
395 |
edef[rtype] = value |
|
396 |
elif to_build.has_key(str(rhs)): |
|
397 |
# create a relation between two newly created variables |
|
398 |
self.add_relation_def((edef, rtype, to_build[rhs.name])) |
|
399 |
else: |
|
400 |
to_select.setdefault(edef, []).append( (rtype, rhs, 0) ) |
|
401 |
return to_select |
|
402 |
||
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
403 |
|
0 | 404 |
def add_entity_def(self, edef): |
405 |
"""add an entity definition to build""" |
|
406 |
edef.querier_pending_relations = {} |
|
407 |
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
|
408 |
|
0 | 409 |
def add_relation_def(self, rdef): |
410 |
"""add an relation definition to build""" |
|
411 |
self.r_defs.append(rdef) |
|
412 |
if not isinstance(rdef[0], int): |
|
413 |
self._r_subj_index.setdefault(rdef[0], []).append(rdef) |
|
414 |
if not isinstance(rdef[2], int): |
|
415 |
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
|
416 |
|
0 | 417 |
def substitute_entity_def(self, edef, edefs): |
418 |
"""substitute an incomplete entity definition by a list of complete |
|
419 |
equivalents |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
420 |
|
0 | 421 |
e.g. on queries such as :: |
422 |
INSERT Personne X, Societe Y: X nom N, Y nom 'toto', X travaille Y |
|
423 |
WHERE U login 'admin', U login N |
|
424 |
||
425 |
X will be inserted as many times as U exists, and so the X travaille Y |
|
426 |
relations as to be added as many time as X is inserted |
|
427 |
""" |
|
428 |
if not edefs or not self.e_defs: |
|
429 |
# no result, no entity will be created |
|
430 |
self.e_defs = () |
|
431 |
return |
|
432 |
# first remove the incomplete entity definition |
|
433 |
colidx = self.e_defs[0].index(edef) |
|
434 |
for i, row in enumerate(self.e_defs[:]): |
|
435 |
self.e_defs[i][colidx] = edefs[0] |
|
436 |
samplerow = self.e_defs[i] |
|
437 |
for edef in edefs[1:]: |
|
438 |
row = samplerow[:] |
|
439 |
row[colidx] = edef |
|
440 |
self.e_defs.append(row) |
|
441 |
# now, see if this entity def is referenced as subject in some relation |
|
442 |
# definition |
|
443 |
if self._r_subj_index.has_key(edef): |
|
444 |
for rdef in self._r_subj_index[edef]: |
|
445 |
expanded = self._expanded(rdef) |
|
446 |
result = [] |
|
447 |
for exp_rdef in expanded: |
|
448 |
for edef in edefs: |
|
449 |
result.append( (edef, exp_rdef[1], exp_rdef[2]) ) |
|
450 |
self._expanded_r_defs[rdef] = result |
|
451 |
# and finally, see if this entity def is referenced as object in some |
|
452 |
# relation definition |
|
453 |
if self._r_obj_index.has_key(edef): |
|
454 |
for rdef in self._r_obj_index[edef]: |
|
455 |
expanded = self._expanded(rdef) |
|
456 |
result = [] |
|
457 |
for exp_rdef in expanded: |
|
458 |
for edef in edefs: |
|
459 |
result.append( (exp_rdef[0], exp_rdef[1], edef) ) |
|
460 |
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
|
461 |
|
0 | 462 |
def _expanded(self, rdef): |
463 |
"""return expanded value for the given relation definition""" |
|
464 |
try: |
|
465 |
return self._expanded_r_defs[rdef] |
|
466 |
except KeyError: |
|
467 |
self.r_defs.remove(rdef) |
|
468 |
return [rdef] |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
469 |
|
0 | 470 |
def relation_defs(self): |
471 |
"""return the list for relation definitions to insert""" |
|
472 |
for rdefs in self._expanded_r_defs.values(): |
|
473 |
for rdef in rdefs: |
|
474 |
yield rdef |
|
475 |
for rdef in self.r_defs: |
|
476 |
yield rdef |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
477 |
|
0 | 478 |
def insert_entity_defs(self): |
479 |
"""return eids of inserted entities in a suitable form for the resulting |
|
480 |
result set, e.g.: |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
481 |
|
0 | 482 |
e.g. on queries such as :: |
483 |
INSERT Personne X, Societe Y: X nom N, Y nom 'toto', X travaille Y |
|
484 |
WHERE U login 'admin', U login N |
|
485 |
||
486 |
if there is two entities matching U, the result set will look like |
|
487 |
[(eidX1, eidY1), (eidX2, eidY2)] |
|
488 |
""" |
|
489 |
session = self.session |
|
490 |
repo = session.repo |
|
491 |
results = [] |
|
492 |
for row in self.e_defs: |
|
493 |
results.append([repo.glob_add_entity(session, edef) |
|
494 |
for edef in row]) |
|
495 |
return results |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
496 |
|
0 | 497 |
def insert_relation_defs(self): |
498 |
session = self.session |
|
499 |
repo = session.repo |
|
500 |
for subj, rtype, obj in self.relation_defs(): |
|
501 |
# if a string is given into args instead of an int, we get it here |
|
502 |
if isinstance(subj, basestring): |
|
503 |
subj = typed_eid(subj) |
|
504 |
elif not isinstance(subj, (int, long)): |
|
505 |
subj = subj.eid |
|
506 |
if isinstance(obj, basestring): |
|
507 |
obj = typed_eid(obj) |
|
508 |
elif not isinstance(obj, (int, long)): |
|
509 |
obj = obj.eid |
|
510 |
if repo.schema.rschema(rtype).inlined: |
|
2680
66472d85d548
[R] use req.entity_from_eid
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2646
diff
changeset
|
511 |
entity = session.entity_from_eid(subj) |
0 | 512 |
entity[rtype] = obj |
3171
b10f0c1f3fe4
[repo] oops, glob_update_entity takes a list of edited attributes has third argument
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3109
diff
changeset
|
513 |
repo.glob_update_entity(session, entity, set((rtype,))) |
0 | 514 |
else: |
515 |
repo.glob_add_relation(session, subj, rtype, obj) |
|
516 |
||
517 |
||
518 |
class QuerierHelper(object): |
|
519 |
"""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
|
520 |
|
0 | 521 |
def __init__(self, repo, schema): |
522 |
# system info helper |
|
523 |
self._repo = repo |
|
2476
1294a6bdf3bf
application -> instance where it makes sense
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2101
diff
changeset
|
524 |
# instance schema |
0 | 525 |
self.set_schema(schema) |
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
526 |
|
0 | 527 |
def set_schema(self, schema): |
528 |
self.schema = schema |
|
3240
8604a15995d1
refactor so that rql rewriter may be used outside the server. Enhance it to be usable for RRQLExpression as well
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3171
diff
changeset
|
529 |
repo = self._repo |
0 | 530 |
# rql parsing / analysing helper |
3240
8604a15995d1
refactor so that rql rewriter may be used outside the server. Enhance it to be usable for RRQLExpression as well
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3171
diff
changeset
|
531 |
self.solutions = repo.vreg.solutions |
8604a15995d1
refactor so that rql rewriter may be used outside the server. Enhance it to be usable for RRQLExpression as well
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3171
diff
changeset
|
532 |
self._rql_cache = Cache(repo.config['rql-cache-size']) |
0 | 533 |
self.cache_hit, self.cache_miss = 0, 0 |
534 |
# rql planner |
|
535 |
# note: don't use repo.sources, may not be built yet, and also "admin" |
|
536 |
# isn't an actual source |
|
3240
8604a15995d1
refactor so that rql rewriter may be used outside the server. Enhance it to be usable for RRQLExpression as well
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3171
diff
changeset
|
537 |
rqlhelper = repo.vreg.rqlhelper |
8604a15995d1
refactor so that rql rewriter may be used outside the server. Enhance it to be usable for RRQLExpression as well
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3171
diff
changeset
|
538 |
self._parse = rqlhelper.parse |
8604a15995d1
refactor so that rql rewriter may be used outside the server. Enhance it to be usable for RRQLExpression as well
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3171
diff
changeset
|
539 |
self._annotate = rqlhelper.annotate |
8604a15995d1
refactor so that rql rewriter may be used outside the server. Enhance it to be usable for RRQLExpression as well
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3171
diff
changeset
|
540 |
if len([uri for uri in repo.config.sources() if uri != 'admin']) < 2: |
0 | 541 |
from cubicweb.server.ssplanner import SSPlanner |
3240
8604a15995d1
refactor so that rql rewriter may be used outside the server. Enhance it to be usable for RRQLExpression as well
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3171
diff
changeset
|
542 |
self._planner = SSPlanner(schema, rqlhelper) |
0 | 543 |
else: |
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
544 |
from cubicweb.server.msplanner import MSPlanner |
3240
8604a15995d1
refactor so that rql rewriter may be used outside the server. Enhance it to be usable for RRQLExpression as well
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3171
diff
changeset
|
545 |
self._planner = MSPlanner(schema, rqlhelper) |
0 | 546 |
# sql generation annotator |
547 |
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
|
548 |
|
0 | 549 |
def parse(self, rql, annotate=False): |
550 |
"""return a rql syntax tree for the given rql""" |
|
551 |
try: |
|
3240
8604a15995d1
refactor so that rql rewriter may be used outside the server. Enhance it to be usable for RRQLExpression as well
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3171
diff
changeset
|
552 |
return self._parse(unicode(rql), annotate=annotate) |
0 | 553 |
except UnicodeError: |
554 |
raise RQLSyntaxError(rql) |
|
555 |
||
556 |
def plan_factory(self, rqlst, args, session): |
|
557 |
"""create an execution plan for an INSERT RQL query""" |
|
558 |
if rqlst.TYPE == 'insert': |
|
559 |
return InsertPlan(self, rqlst, args, session) |
|
560 |
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
|
561 |
|
0 | 562 |
def execute(self, session, rql, args=None, eid_key=None, build_descr=True): |
563 |
"""execute a rql query, return resulting rows and their description in |
|
564 |
a `ResultSet` object |
|
565 |
||
566 |
* `rql` should be an unicode string or a plain ascii string |
|
567 |
* `args` the optional parameters dictionary associated to the query |
|
568 |
* `build_descr` is a boolean flag indicating if the description should |
|
569 |
be built on select queries (if false, the description will be en empty |
|
570 |
list) |
|
571 |
* `eid_key` must be both a key in args and a substitution in the rql |
|
572 |
query. It should be used to enhance cacheability of rql queries. |
|
573 |
It may be a tuple for keys in args. |
|
574 |
eid_key must be providen in case where a eid substitution is providen |
|
575 |
and resolve some ambiguity in the possible solutions infered for each |
|
576 |
variable in the query. |
|
577 |
||
578 |
on INSERT queries, there will be on row with the eid of each inserted |
|
579 |
entity |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
580 |
|
0 | 581 |
result for DELETE and SET queries is undefined yet |
582 |
||
583 |
to maximize the rql parsing/analyzing cache performance, you should |
|
584 |
always use substitute arguments in queries (eg avoid query such as |
|
585 |
'Any X WHERE X eid 123'!) |
|
586 |
""" |
|
2621
1b9d08840a0e
R [querier] debugging tweaks
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2601
diff
changeset
|
587 |
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
|
588 |
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
|
589 |
print '*'*80 |
2646
d2874ddd4347
#F [querier] debugging tweak
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2629
diff
changeset
|
590 |
print 'querier input', rql, args |
0 | 591 |
# parse the query and binds variables |
592 |
if eid_key is not None: |
|
593 |
if not isinstance(eid_key, (tuple, list)): |
|
594 |
eid_key = (eid_key,) |
|
595 |
cachekey = [rql] |
|
596 |
for key in eid_key: |
|
597 |
try: |
|
598 |
etype = self._repo.type_from_eid(args[key], session) |
|
599 |
except KeyError: |
|
600 |
raise QueryError('bad cache key %s (no value)' % key) |
|
601 |
except TypeError: |
|
1954 | 602 |
raise QueryError('bad cache key %s (value: %r)' % ( |
603 |
key, args[key])) |
|
0 | 604 |
except UnknownEid: |
605 |
# we want queries such as "Any X WHERE X eid 9999" |
|
606 |
# return an empty result instead of raising UnknownEid |
|
607 |
return empty_rset(session, rql, args) |
|
608 |
cachekey.append(etype) |
|
3109
e7e1bb06b716
ensure eid given in arguments will be returned correctly typed (though only if they are in the cachekey for now)
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2680
diff
changeset
|
609 |
# ensure eid is correctly typed in args |
e7e1bb06b716
ensure eid given in arguments will be returned correctly typed (though only if they are in the cachekey for now)
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2680
diff
changeset
|
610 |
args[key] = typed_eid(args[key]) |
0 | 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() |
|
3240
8604a15995d1
refactor so that rql rewriter may be used outside the server. Enhance it to be usable for RRQLExpression as well
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3171
diff
changeset
|
643 |
self._annotate(rqlst) |
0 | 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) |