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