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