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