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