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