author | Adrien Di Mascio <Adrien.DiMascio@logilab.fr> |
Mon, 12 Apr 2010 08:22:37 +0200 | |
branch | stable |
changeset 5213 | 8604000bf3b2 |
parent 5168 | 1ab032df5ca3 |
child 5177 | 395e1ff018ae |
child 5419 | 0b7805928a27 |
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(): |
c8c0e10dbd97
[read security] minor optimizations
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4843
diff
changeset
|
329 |
for rel in var.stinfo['uidrels']: |
c8c0e10dbd97
[read security] minor optimizations
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4843
diff
changeset
|
330 |
const = rel.children[1].children[0] |
4957
25f20adba80f
[security] take care uidrels may contains a relation targetting something else than a constant node (eg IN function)
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4955
diff
changeset
|
331 |
try: |
25f20adba80f
[security] take care uidrels may contains a relation targetting something else than a constant node (eg IN function)
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4955
diff
changeset
|
332 |
varkwargs[var.name] = typed_eid(const.eval(self.args)) |
25f20adba80f
[security] take care uidrels may contains a relation targetting something else than a constant node (eg IN function)
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4955
diff
changeset
|
333 |
break |
25f20adba80f
[security] take care uidrels may contains a relation targetting something else than a constant node (eg IN function)
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4955
diff
changeset
|
334 |
except AttributeError: |
25f20adba80f
[security] take care uidrels may contains a relation targetting something else than a constant node (eg IN function)
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4955
diff
changeset
|
335 |
#from rql.nodes import Function |
25f20adba80f
[security] take care uidrels may contains a relation targetting something else than a constant node (eg IN function)
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4955
diff
changeset
|
336 |
#assert isinstance(const, Function) |
25f20adba80f
[security] take care uidrels may contains a relation targetting something else than a constant node (eg IN function)
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4955
diff
changeset
|
337 |
# X eid IN(...) |
25f20adba80f
[security] take care uidrels may contains a relation targetting something else than a constant node (eg IN function)
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4955
diff
changeset
|
338 |
pass |
0 | 339 |
# dictionnary of variables restricted for security reason |
340 |
localchecks = {} |
|
341 |
restricted_vars = set() |
|
342 |
newsolutions = [] |
|
343 |
for solution in rqlst.solutions: |
|
344 |
try: |
|
345 |
localcheck = check_read_access(schema, user, rqlst, solution) |
|
346 |
except Unauthorized, ex: |
|
347 |
msg = 'remove %s from solutions since %s has no %s access to %s' |
|
348 |
msg %= (solution, user.login, ex.args[0], ex.args[1]) |
|
349 |
msgs.append(msg) |
|
350 |
LOGGER.info(msg) |
|
351 |
else: |
|
352 |
newsolutions.append(solution) |
|
4953
c8c0e10dbd97
[read security] minor optimizations
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4843
diff
changeset
|
353 |
# 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
|
354 |
# are specified by eid in query'args |
c8c0e10dbd97
[read security] minor optimizations
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4843
diff
changeset
|
355 |
for varname, eid in varkwargs.iteritems(): |
c8c0e10dbd97
[read security] minor optimizations
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4843
diff
changeset
|
356 |
try: |
c8c0e10dbd97
[read security] minor optimizations
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4843
diff
changeset
|
357 |
rqlexprs = localcheck.pop(varname) |
c8c0e10dbd97
[read security] minor optimizations
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4843
diff
changeset
|
358 |
except KeyError: |
c8c0e10dbd97
[read security] minor optimizations
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4843
diff
changeset
|
359 |
continue |
c8c0e10dbd97
[read security] minor optimizations
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4843
diff
changeset
|
360 |
if eid in neweids: |
c8c0e10dbd97
[read security] minor optimizations
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4843
diff
changeset
|
361 |
continue |
c8c0e10dbd97
[read security] minor optimizations
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4843
diff
changeset
|
362 |
for rqlexpr in rqlexprs: |
c8c0e10dbd97
[read security] minor optimizations
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4843
diff
changeset
|
363 |
if rqlexpr.check(session, eid): |
c8c0e10dbd97
[read security] minor optimizations
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4843
diff
changeset
|
364 |
break |
c8c0e10dbd97
[read security] minor optimizations
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4843
diff
changeset
|
365 |
else: |
c8c0e10dbd97
[read security] minor optimizations
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4843
diff
changeset
|
366 |
raise Unauthorized() |
0 | 367 |
restricted_vars.update(localcheck) |
368 |
localchecks.setdefault(tuple(localcheck.iteritems()), []).append(solution) |
|
369 |
# raise Unautorized exception if the user can't access to any solution |
|
370 |
if not newsolutions: |
|
371 |
raise Unauthorized('\n'.join(msgs)) |
|
372 |
rqlst.set_possible_types(newsolutions) |
|
373 |
return localchecks, restricted_vars |
|
374 |
||
375 |
def finalize(self, select, solutions, insertedvars): |
|
376 |
rqlst = Union() |
|
377 |
rqlst.append(select) |
|
378 |
for mainvarname, rschema, newvarname in insertedvars: |
|
379 |
nvartype = str(rschema.objects(solutions[0][mainvarname])[0]) |
|
380 |
for sol in solutions: |
|
381 |
sol[newvarname] = nvartype |
|
382 |
select.clean_solutions(solutions) |
|
383 |
self.rqlhelper.annotate(rqlst) |
|
384 |
self.preprocess(rqlst, security=False) |
|
385 |
return rqlst |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
386 |
|
4759 | 387 |
|
0 | 388 |
class InsertPlan(ExecutionPlan): |
389 |
"""an execution model specific to the INSERT rql query |
|
390 |
""" |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
391 |
|
0 | 392 |
def __init__(self, querier, rqlst, args, session): |
393 |
ExecutionPlan.__init__(self, querier, rqlst, args, session) |
|
394 |
# save originaly selected variable, we may modify this |
|
395 |
# dictionary for substitution (query parameters) |
|
396 |
self.selected = rqlst.selection |
|
397 |
# list of new or updated entities definition (utils.Entity) |
|
398 |
self.e_defs = [[]] |
|
399 |
# list of new relation definition (3-uple (from_eid, r_type, to_eid) |
|
400 |
self.r_defs = [] |
|
401 |
# indexes to track entity definitions bound to relation definitions |
|
402 |
self._r_subj_index = {} |
|
403 |
self._r_obj_index = {} |
|
404 |
self._expanded_r_defs = {} |
|
405 |
||
406 |
def add_entity_def(self, edef): |
|
407 |
"""add an entity definition to build""" |
|
408 |
edef.querier_pending_relations = {} |
|
409 |
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
|
410 |
|
0 | 411 |
def add_relation_def(self, rdef): |
412 |
"""add an relation definition to build""" |
|
413 |
self.r_defs.append(rdef) |
|
414 |
if not isinstance(rdef[0], int): |
|
415 |
self._r_subj_index.setdefault(rdef[0], []).append(rdef) |
|
416 |
if not isinstance(rdef[2], int): |
|
417 |
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
|
418 |
|
0 | 419 |
def substitute_entity_def(self, edef, edefs): |
420 |
"""substitute an incomplete entity definition by a list of complete |
|
421 |
equivalents |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
422 |
|
0 | 423 |
e.g. on queries such as :: |
424 |
INSERT Personne X, Societe Y: X nom N, Y nom 'toto', X travaille Y |
|
425 |
WHERE U login 'admin', U login N |
|
426 |
||
427 |
X will be inserted as many times as U exists, and so the X travaille Y |
|
428 |
relations as to be added as many time as X is inserted |
|
429 |
""" |
|
430 |
if not edefs or not self.e_defs: |
|
431 |
# no result, no entity will be created |
|
432 |
self.e_defs = () |
|
433 |
return |
|
434 |
# first remove the incomplete entity definition |
|
435 |
colidx = self.e_defs[0].index(edef) |
|
436 |
for i, row in enumerate(self.e_defs[:]): |
|
437 |
self.e_defs[i][colidx] = edefs[0] |
|
438 |
samplerow = self.e_defs[i] |
|
439 |
for edef in edefs[1:]: |
|
440 |
row = samplerow[:] |
|
441 |
row[colidx] = edef |
|
442 |
self.e_defs.append(row) |
|
443 |
# now, see if this entity def is referenced as subject in some relation |
|
444 |
# definition |
|
445 |
if self._r_subj_index.has_key(edef): |
|
446 |
for rdef in self._r_subj_index[edef]: |
|
447 |
expanded = self._expanded(rdef) |
|
448 |
result = [] |
|
449 |
for exp_rdef in expanded: |
|
450 |
for edef in edefs: |
|
451 |
result.append( (edef, exp_rdef[1], exp_rdef[2]) ) |
|
452 |
self._expanded_r_defs[rdef] = result |
|
453 |
# and finally, see if this entity def is referenced as object in some |
|
454 |
# relation definition |
|
455 |
if self._r_obj_index.has_key(edef): |
|
456 |
for rdef in self._r_obj_index[edef]: |
|
457 |
expanded = self._expanded(rdef) |
|
458 |
result = [] |
|
459 |
for exp_rdef in expanded: |
|
460 |
for edef in edefs: |
|
461 |
result.append( (exp_rdef[0], exp_rdef[1], edef) ) |
|
462 |
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
|
463 |
|
0 | 464 |
def _expanded(self, rdef): |
465 |
"""return expanded value for the given relation definition""" |
|
466 |
try: |
|
467 |
return self._expanded_r_defs[rdef] |
|
468 |
except KeyError: |
|
469 |
self.r_defs.remove(rdef) |
|
470 |
return [rdef] |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
471 |
|
0 | 472 |
def relation_defs(self): |
473 |
"""return the list for relation definitions to insert""" |
|
474 |
for rdefs in self._expanded_r_defs.values(): |
|
475 |
for rdef in rdefs: |
|
476 |
yield rdef |
|
477 |
for rdef in self.r_defs: |
|
478 |
yield rdef |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
479 |
|
0 | 480 |
def insert_entity_defs(self): |
481 |
"""return eids of inserted entities in a suitable form for the resulting |
|
482 |
result set, e.g.: |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
483 |
|
0 | 484 |
e.g. on queries such as :: |
485 |
INSERT Personne X, Societe Y: X nom N, Y nom 'toto', X travaille Y |
|
486 |
WHERE U login 'admin', U login N |
|
487 |
||
488 |
if there is two entities matching U, the result set will look like |
|
489 |
[(eidX1, eidY1), (eidX2, eidY2)] |
|
490 |
""" |
|
491 |
session = self.session |
|
492 |
repo = session.repo |
|
493 |
results = [] |
|
494 |
for row in self.e_defs: |
|
495 |
results.append([repo.glob_add_entity(session, edef) |
|
496 |
for edef in row]) |
|
497 |
return results |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
498 |
|
0 | 499 |
def insert_relation_defs(self): |
500 |
session = self.session |
|
501 |
repo = session.repo |
|
502 |
for subj, rtype, obj in self.relation_defs(): |
|
503 |
# if a string is given into args instead of an int, we get it here |
|
504 |
if isinstance(subj, basestring): |
|
505 |
subj = typed_eid(subj) |
|
506 |
elif not isinstance(subj, (int, long)): |
|
507 |
subj = subj.eid |
|
508 |
if isinstance(obj, basestring): |
|
509 |
obj = typed_eid(obj) |
|
510 |
elif not isinstance(obj, (int, long)): |
|
511 |
obj = obj.eid |
|
512 |
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
|
513 |
entity = session.entity_from_eid(subj) |
0 | 514 |
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
|
515 |
repo.glob_update_entity(session, entity, set((rtype,))) |
0 | 516 |
else: |
517 |
repo.glob_add_relation(session, subj, rtype, obj) |
|
518 |
||
519 |
||
520 |
class QuerierHelper(object): |
|
521 |
"""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
|
522 |
|
0 | 523 |
def __init__(self, repo, schema): |
524 |
# system info helper |
|
525 |
self._repo = repo |
|
2476
1294a6bdf3bf
application -> instance where it makes sense
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2101
diff
changeset
|
526 |
# instance schema |
0 | 527 |
self.set_schema(schema) |
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
528 |
|
0 | 529 |
def set_schema(self, schema): |
530 |
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
|
531 |
repo = self._repo |
0 | 532 |
# 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
|
533 |
self.solutions = repo.vreg.solutions |
8604a15995d1
refactor so that rql rewriter may be used outside the server. Enhance it to be usable for RRQLExpression as well
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3171
diff
changeset
|
534 |
self._rql_cache = Cache(repo.config['rql-cache-size']) |
0 | 535 |
self.cache_hit, self.cache_miss = 0, 0 |
536 |
# rql planner |
|
537 |
# note: don't use repo.sources, may not be built yet, and also "admin" |
|
538 |
# 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
|
539 |
rqlhelper = repo.vreg.rqlhelper |
8604a15995d1
refactor so that rql rewriter may be used outside the server. Enhance it to be usable for RRQLExpression as well
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3171
diff
changeset
|
540 |
self._parse = rqlhelper.parse |
8604a15995d1
refactor so that rql rewriter may be used outside the server. Enhance it to be usable for RRQLExpression as well
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3171
diff
changeset
|
541 |
self._annotate = rqlhelper.annotate |
8604a15995d1
refactor so that rql rewriter may be used outside the server. Enhance it to be usable for RRQLExpression as well
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
3171
diff
changeset
|
542 |
if len([uri for uri in repo.config.sources() if uri != 'admin']) < 2: |
0 | 543 |
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
|
544 |
self._planner = SSPlanner(schema, rqlhelper) |
0 | 545 |
else: |
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
546 |
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
|
547 |
self._planner = MSPlanner(schema, rqlhelper) |
0 | 548 |
# sql generation annotator |
549 |
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
|
550 |
|
0 | 551 |
def parse(self, rql, annotate=False): |
552 |
"""return a rql syntax tree for the given rql""" |
|
553 |
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
|
554 |
return self._parse(unicode(rql), annotate=annotate) |
0 | 555 |
except UnicodeError: |
556 |
raise RQLSyntaxError(rql) |
|
557 |
||
558 |
def plan_factory(self, rqlst, args, session): |
|
559 |
"""create an execution plan for an INSERT RQL query""" |
|
560 |
if rqlst.TYPE == 'insert': |
|
561 |
return InsertPlan(self, rqlst, args, session) |
|
562 |
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
|
563 |
|
0 | 564 |
def execute(self, session, rql, args=None, eid_key=None, build_descr=True): |
565 |
"""execute a rql query, return resulting rows and their description in |
|
566 |
a `ResultSet` object |
|
567 |
||
4654
717310b3d576
docstring improvement
Alexandre Fayolle <alexandre.fayolle@logilab.fr>
parents:
4533
diff
changeset
|
568 |
* `rql` should be an Unicode string or a plain ASCII string |
0 | 569 |
* `args` the optional parameters dictionary associated to the query |
570 |
* `build_descr` is a boolean flag indicating if the description should |
|
571 |
be built on select queries (if false, the description will be en empty |
|
572 |
list) |
|
573 |
* `eid_key` must be both a key in args and a substitution in the rql |
|
574 |
query. It should be used to enhance cacheability of rql queries. |
|
575 |
It may be a tuple for keys in args. |
|
4654
717310b3d576
docstring improvement
Alexandre Fayolle <alexandre.fayolle@logilab.fr>
parents:
4533
diff
changeset
|
576 |
`eid_key` must be provided in cases where a eid substitution is provided |
717310b3d576
docstring improvement
Alexandre Fayolle <alexandre.fayolle@logilab.fr>
parents:
4533
diff
changeset
|
577 |
and resolves ambiguities in the possible solutions inferred for each |
0 | 578 |
variable in the query. |
579 |
||
4654
717310b3d576
docstring improvement
Alexandre Fayolle <alexandre.fayolle@logilab.fr>
parents:
4533
diff
changeset
|
580 |
on INSERT queries, there will be one row with the eid of each inserted |
0 | 581 |
entity |
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1133
diff
changeset
|
582 |
|
0 | 583 |
result for DELETE and SET queries is undefined yet |
584 |
||
585 |
to maximize the rql parsing/analyzing cache performance, you should |
|
4654
717310b3d576
docstring improvement
Alexandre Fayolle <alexandre.fayolle@logilab.fr>
parents:
4533
diff
changeset
|
586 |
always use substitute arguments in queries (i.e. avoid query such as |
0 | 587 |
'Any X WHERE X eid 123'!) |
588 |
""" |
|
2621
1b9d08840a0e
R [querier] debugging tweaks
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2601
diff
changeset
|
589 |
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
|
590 |
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
|
591 |
print '*'*80 |
2646
d2874ddd4347
#F [querier] debugging tweak
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2629
diff
changeset
|
592 |
print 'querier input', rql, args |
0 | 593 |
# parse the query and binds variables |
594 |
if eid_key is not None: |
|
595 |
if not isinstance(eid_key, (tuple, list)): |
|
596 |
eid_key = (eid_key,) |
|
597 |
cachekey = [rql] |
|
598 |
for key in eid_key: |
|
599 |
try: |
|
600 |
etype = self._repo.type_from_eid(args[key], session) |
|
601 |
except KeyError: |
|
602 |
raise QueryError('bad cache key %s (no value)' % key) |
|
603 |
except TypeError: |
|
1954 | 604 |
raise QueryError('bad cache key %s (value: %r)' % ( |
605 |
key, args[key])) |
|
0 | 606 |
except UnknownEid: |
607 |
# we want queries such as "Any X WHERE X eid 9999" |
|
608 |
# return an 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) |
0 | 610 |
cachekey.append(etype) |
3109
e7e1bb06b716
ensure eid given in arguments will be returned correctly typed (though only if they are in the cachekey for now)
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2680
diff
changeset
|
611 |
# ensure eid is correctly typed in args |
e7e1bb06b716
ensure eid given in arguments will be returned correctly typed (though only if they are in the cachekey for now)
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2680
diff
changeset
|
612 |
args[key] = typed_eid(args[key]) |
0 | 613 |
cachekey = tuple(cachekey) |
614 |
else: |
|
615 |
cachekey = rql |
|
616 |
try: |
|
617 |
rqlst = self._rql_cache[cachekey] |
|
618 |
self.cache_hit += 1 |
|
619 |
except KeyError: |
|
620 |
self.cache_miss += 1 |
|
621 |
rqlst = self.parse(rql) |
|
622 |
try: |
|
623 |
self.solutions(session, rqlst, args) |
|
624 |
except UnknownEid: |
|
4843
5f7363416765
fix hooks control method name + other litle cleanups
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4835
diff
changeset
|
625 |
# 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
|
626 |
# empty result instead of raising UnknownEid |
4722
9c13d5db03d9
pylint suggested refactorings
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4719
diff
changeset
|
627 |
return empty_rset(rql, args, rqlst) |
0 | 628 |
self._rql_cache[cachekey] = rqlst |
629 |
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
|
630 |
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
|
631 |
if session.read_security: |
0 | 632 |
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
|
633 |
# 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
|
634 |
# be released until commit/rollback |
0 | 635 |
session.mode = 'write' |
636 |
cachekey = None |
|
637 |
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
|
638 |
if session.read_security: |
0 | 639 |
for select in rqlst.children: |
640 |
check_no_password_selected(select) |
|
641 |
# on select query, always copy the cached rqlst so we don't have to |
|
642 |
# bother modifying it. This is not necessary on write queries since |
|
643 |
# a new syntax tree is built from them. |
|
644 |
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
|
645 |
self._annotate(rqlst) |
0 | 646 |
# make an execution plan |
647 |
plan = self.plan_factory(rqlst, args, session) |
|
648 |
plan.cache_key = cachekey |
|
649 |
self._planner.build_plan(plan) |
|
650 |
# execute the plan |
|
651 |
try: |
|
652 |
results = plan.execute() |
|
653 |
except Unauthorized: |
|
654 |
# XXX this could be done in security's after_add_relation hooks |
|
655 |
# since it's actually realy only needed there (other relations |
|
656 |
# security is done *before* actual changes, and add/update entity |
|
657 |
# security is done after changes but in an operation, and exception |
|
4533 | 658 |
# generated in operation's events properly generate a rollback on |
0 | 659 |
# the session). Even though, this is done here for a better |
660 |
# consistency: getting an Unauthorized exception means the |
|
661 |
# transaction has been rollbacked |
|
4532
85116e75f561
fix auto-rollback on unauthorized error:
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4252
diff
changeset
|
662 |
# |
85116e75f561
fix auto-rollback on unauthorized error:
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4252
diff
changeset
|
663 |
# notes: |
85116e75f561
fix auto-rollback on unauthorized error:
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4252
diff
changeset
|
664 |
# * 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
|
665 |
# 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
|
666 |
# * 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
|
667 |
# by the session |
85116e75f561
fix auto-rollback on unauthorized error:
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4252
diff
changeset
|
668 |
if session.commit_state is None: |
85116e75f561
fix auto-rollback on unauthorized error:
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
4252
diff
changeset
|
669 |
session.rollback(reset_pool=False) |
0 | 670 |
raise |
671 |
# build a description for the results if necessary |
|
672 |
descr = () |
|
673 |
if build_descr: |
|
674 |
if rqlst.TYPE == 'select': |
|
675 |
# sample selection |
|
676 |
descr = session.build_description(orig_rqlst, args, results) |
|
677 |
elif rqlst.TYPE == 'insert': |
|
678 |
# on insert plan, some entities may have been auto-casted, |
|
679 |
# so compute description manually even if there is only |
|
680 |
# one solution |
|
681 |
basedescr = [None] * len(plan.selected) |
|
682 |
todetermine = zip(xrange(len(plan.selected)), repeat(False)) |
|
683 |
descr = session._build_descr(results, basedescr, todetermine) |
|
684 |
# FIXME: get number of affected entities / relations on non |
|
685 |
# selection queries ? |
|
686 |
# return a result set object |
|
687 |
return ResultSet(results, rql, args, descr, eid_key, orig_rqlst) |
|
688 |
||
689 |
from logging import getLogger |
|
690 |
from cubicweb import set_log_methods |
|
691 |
LOGGER = getLogger('cubicweb.querier') |
|
692 |
set_log_methods(QuerierHelper, LOGGER) |