author | Adrien Di Mascio <Adrien.DiMascio@logilab.fr> |
Wed, 05 Aug 2009 09:14:34 +0200 | |
changeset 3386 | ab797c5374b7 |
parent 2691 | ade319674170 |
child 2716 | 2f6edb0e9626 |
permissions | -rw-r--r-- |
0 | 1 |
"""classes to define schemas for CubicWeb |
2 |
||
3 |
:organization: Logilab |
|
1977
606923dff11b
big bunch of copyright / docstring update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1498
diff
changeset
|
4 |
:copyright: 2001-2009 LOGILAB S.A. (Paris, FRANCE), license is LGPL v2. |
0 | 5 |
: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:
1498
diff
changeset
|
6 |
:license: GNU Lesser General Public License, v2.1 - http://www.gnu.org/licenses |
0 | 7 |
""" |
8 |
__docformat__ = "restructuredtext en" |
|
2142
098aa2075903
include_schema_files is useless
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
9 |
_ = unicode |
0 | 10 |
|
11 |
import re |
|
2147
476a75ede2cc
merge and add missing import in schema.py
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2142
diff
changeset
|
12 |
from os.path import join |
0 | 13 |
from logging import getLogger |
1133 | 14 |
from warnings import warn |
0 | 15 |
|
624
258e5692ae06
provide a new RichString attribute type
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
479
diff
changeset
|
16 |
from logilab.common.decorators import cached, clear_cache, monkeypatch |
2613
5e19c2bb370e
R [all] logilab.common 0.44 provides only deprecated
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
2531
diff
changeset
|
17 |
from logilab.common.deprecation import deprecated |
0 | 18 |
from logilab.common.compat import any |
19 |
||
2531
531ea4e7013e
[cleanup] nicer imports
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
2526
diff
changeset
|
20 |
from yams import BadSchemaDefinition, buildobjs as ybo |
0 | 21 |
from yams.schema import Schema, ERSchema, EntitySchema, RelationSchema |
2531
531ea4e7013e
[cleanup] nicer imports
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
2526
diff
changeset
|
22 |
from yams.constraints import (BaseConstraint, StaticVocabularyConstraint, |
531ea4e7013e
[cleanup] nicer imports
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
2526
diff
changeset
|
23 |
FormatConstraint) |
531ea4e7013e
[cleanup] nicer imports
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
2526
diff
changeset
|
24 |
from yams.reader import (CONSTRAINTS, PyFileReader, SchemaLoader, |
531ea4e7013e
[cleanup] nicer imports
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
2526
diff
changeset
|
25 |
obsolete as yobsolete, cleanup_sys_modules) |
0 | 26 |
|
27 |
from rql import parse, nodes, RQLSyntaxError, TypeResolverException |
|
28 |
||
29 |
from cubicweb import ETYPE_NAME_MAP, ValidationError, Unauthorized |
|
1138
22f634977c95
make pylint happy, fix some bugs on the way
sylvain.thenault@logilab.fr
parents:
1133
diff
changeset
|
30 |
from cubicweb import set_log_methods |
0 | 31 |
|
1016
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
745
diff
changeset
|
32 |
# XXX <3.2 bw compat |
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
745
diff
changeset
|
33 |
from yams import schema |
26387b836099
use datetime instead of mx.DateTime
sylvain.thenault@logilab.fr
parents:
745
diff
changeset
|
34 |
schema.use_py_datetime() |
1451 | 35 |
nodes.use_py_datetime() |
0 | 36 |
|
2596
d02eed70937f
[R repo, schema] use VIRTUAL_RTYPES const
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2531
diff
changeset
|
37 |
PURE_VIRTUAL_RTYPES = set(('identity', 'has_text',)) |
d02eed70937f
[R repo, schema] use VIRTUAL_RTYPES const
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2531
diff
changeset
|
38 |
VIRTUAL_RTYPES = set(('eid', 'identity', 'has_text',)) |
d02eed70937f
[R repo, schema] use VIRTUAL_RTYPES const
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2531
diff
changeset
|
39 |
|
2126
a25859917ccc
stop using meta attribute from yams schema. Use instead sets defining meta relations and another defining schema types. Refactor various schema view based on this
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
40 |
# set of meta-relations available for every entity types |
2622
3c7edaa6c6d2
oops, should have been in a earlier commit (META_RELATION_TYPES renaming)
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2616
diff
changeset
|
41 |
META_RTYPES = set(( |
2126
a25859917ccc
stop using meta attribute from yams schema. Use instead sets defining meta relations and another defining schema types. Refactor various schema view based on this
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
42 |
'owned_by', 'created_by', 'is', 'is_instance_of', 'identity', |
2456
aa25d6b244c8
new cwuri metadata + a few tests fixes on the way
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
2437
diff
changeset
|
43 |
'eid', 'creation_date', 'modification_date', 'has_text', 'cwuri', |
2184 | 44 |
)) |
0 | 45 |
|
2126
a25859917ccc
stop using meta attribute from yams schema. Use instead sets defining meta relations and another defining schema types. Refactor various schema view based on this
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
46 |
# set of entity and relation types used to build the schema |
a25859917ccc
stop using meta attribute from yams schema. Use instead sets defining meta relations and another defining schema types. Refactor various schema view based on this
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
47 |
SCHEMA_TYPES = set(( |
a25859917ccc
stop using meta attribute from yams schema. Use instead sets defining meta relations and another defining schema types. Refactor various schema view based on this
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
48 |
'CWEType', 'CWRType', 'CWAttribute', 'CWRelation', |
a25859917ccc
stop using meta attribute from yams schema. Use instead sets defining meta relations and another defining schema types. Refactor various schema view based on this
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
49 |
'CWConstraint', 'CWConstraintType', 'RQLExpression', |
a25859917ccc
stop using meta attribute from yams schema. Use instead sets defining meta relations and another defining schema types. Refactor various schema view based on this
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
50 |
'relation_type', 'from_entity', 'to_entity', |
a25859917ccc
stop using meta attribute from yams schema. Use instead sets defining meta relations and another defining schema types. Refactor various schema view based on this
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
51 |
'constrained_by', 'cstrtype', |
a25859917ccc
stop using meta attribute from yams schema. Use instead sets defining meta relations and another defining schema types. Refactor various schema view based on this
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
52 |
)) |
0 | 53 |
|
2142
098aa2075903
include_schema_files is useless
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
54 |
_LOGGER = getLogger('cubicweb.schemaloader') |
0 | 55 |
|
56 |
# schema entities created from serialized schema have an eid rproperty |
|
57 |
ybo.ETYPE_PROPERTIES += ('eid',) |
|
58 |
ybo.RTYPE_PROPERTIES += ('eid',) |
|
59 |
ybo.RDEF_PROPERTIES += ('eid',) |
|
60 |
||
61 |
def bw_normalize_etype(etype): |
|
62 |
if etype in ETYPE_NAME_MAP: |
|
63 |
msg = '%s has been renamed to %s, please update your code' % ( |
|
1451 | 64 |
etype, ETYPE_NAME_MAP[etype]) |
0 | 65 |
warn(msg, DeprecationWarning, stacklevel=4) |
66 |
etype = ETYPE_NAME_MAP[etype] |
|
67 |
return etype |
|
68 |
||
69 |
def display_name(req, key, form=''): |
|
70 |
"""return a internationalized string for the key (schema entity or relation |
|
71 |
name) in a given form |
|
72 |
""" |
|
73 |
assert form in ('', 'plural', 'subject', 'object') |
|
74 |
if form == 'subject': |
|
75 |
form = '' |
|
76 |
if form: |
|
77 |
key = key + '_' + form |
|
78 |
# ensure unicode |
|
79 |
# added .lower() in case no translation are available |
|
80 |
return unicode(req._(key)).lower() |
|
2613
5e19c2bb370e
R [all] logilab.common 0.44 provides only deprecated
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
2531
diff
changeset
|
81 |
__builtins__['display_name'] = deprecated('display_name should be imported from cubicweb.schema')(display_name) |
0 | 82 |
|
83 |
def ERSchema_display_name(self, req, form=''): |
|
84 |
"""return a internationalized string for the entity/relation type name in |
|
85 |
a given form |
|
86 |
""" |
|
87 |
return display_name(req, self.type, form) |
|
88 |
ERSchema.display_name = ERSchema_display_name |
|
89 |
||
90 |
@cached |
|
91 |
def ERSchema_get_groups(self, action): |
|
92 |
"""return the groups authorized to perform <action> on entities of |
|
93 |
this type |
|
94 |
||
95 |
:type action: str |
|
96 |
:param action: the name of a permission |
|
97 |
||
98 |
:rtype: tuple |
|
99 |
:return: names of the groups with the given permission |
|
100 |
""" |
|
101 |
assert action in self.ACTIONS, action |
|
102 |
#assert action in self._groups, '%s %s' % (self, action) |
|
103 |
try: |
|
104 |
return frozenset(g for g in self._groups[action] if isinstance(g, basestring)) |
|
105 |
except KeyError: |
|
106 |
return () |
|
107 |
ERSchema.get_groups = ERSchema_get_groups |
|
108 |
||
109 |
def ERSchema_set_groups(self, action, groups): |
|
110 |
"""set the groups allowed to perform <action> on entities of this type. Don't |
|
111 |
change rql expressions for the same action. |
|
112 |
||
113 |
:type action: str |
|
114 |
:param action: the name of a permission |
|
115 |
||
116 |
:type groups: list or tuple |
|
117 |
:param groups: names of the groups granted to do the given action |
|
118 |
""" |
|
119 |
assert action in self.ACTIONS, action |
|
120 |
clear_cache(self, 'ERSchema_get_groups') |
|
121 |
self._groups[action] = tuple(groups) + self.get_rqlexprs(action) |
|
122 |
ERSchema.set_groups = ERSchema_set_groups |
|
123 |
||
124 |
@cached |
|
125 |
def ERSchema_get_rqlexprs(self, action): |
|
126 |
"""return the rql expressions representing queries to check the user is allowed |
|
127 |
to perform <action> on entities of this type |
|
128 |
||
129 |
:type action: str |
|
130 |
:param action: the name of a permission |
|
131 |
||
132 |
:rtype: tuple |
|
133 |
:return: the rql expressions with the given permission |
|
134 |
""" |
|
135 |
assert action in self.ACTIONS, action |
|
136 |
#assert action in self._rqlexprs, '%s %s' % (self, action) |
|
137 |
try: |
|
138 |
return tuple(g for g in self._groups[action] if not isinstance(g, basestring)) |
|
139 |
except KeyError: |
|
140 |
return () |
|
141 |
ERSchema.get_rqlexprs = ERSchema_get_rqlexprs |
|
142 |
||
143 |
def ERSchema_set_rqlexprs(self, action, rqlexprs): |
|
144 |
"""set the rql expression allowing to perform <action> on entities of this type. Don't |
|
145 |
change groups for the same action. |
|
146 |
||
147 |
:type action: str |
|
148 |
:param action: the name of a permission |
|
149 |
||
150 |
:type rqlexprs: list or tuple |
|
151 |
:param rqlexprs: the rql expressions allowing the given action |
|
152 |
""" |
|
153 |
assert action in self.ACTIONS, action |
|
154 |
clear_cache(self, 'ERSchema_get_rqlexprs') |
|
155 |
self._groups[action] = tuple(self.get_groups(action)) + tuple(rqlexprs) |
|
156 |
ERSchema.set_rqlexprs = ERSchema_set_rqlexprs |
|
157 |
||
158 |
def ERSchema_set_permissions(self, action, permissions): |
|
159 |
"""set the groups and rql expressions allowing to perform <action> on |
|
160 |
entities of this type |
|
161 |
||
162 |
:type action: str |
|
163 |
:param action: the name of a permission |
|
164 |
||
165 |
:type permissions: tuple |
|
166 |
:param permissions: the groups and rql expressions allowing the given action |
|
167 |
""" |
|
168 |
assert action in self.ACTIONS, action |
|
169 |
clear_cache(self, 'ERSchema_get_rqlexprs') |
|
170 |
clear_cache(self, 'ERSchema_get_groups') |
|
171 |
self._groups[action] = tuple(permissions) |
|
172 |
ERSchema.set_permissions = ERSchema_set_permissions |
|
173 |
||
174 |
def ERSchema_has_perm(self, session, action, *args, **kwargs): |
|
175 |
"""return true if the action is granted globaly or localy""" |
|
176 |
try: |
|
177 |
self.check_perm(session, action, *args, **kwargs) |
|
178 |
return True |
|
179 |
except Unauthorized: |
|
180 |
return False |
|
181 |
ERSchema.has_perm = ERSchema_has_perm |
|
182 |
||
183 |
def ERSchema_has_local_role(self, action): |
|
184 |
"""return true if the action *may* be granted localy (eg either rql |
|
185 |
expressions or the owners group are used in security definition) |
|
186 |
||
187 |
XXX this method is only there since we don't know well how to deal with |
|
188 |
'add' action checking. Also find a better name would be nice. |
|
189 |
""" |
|
190 |
assert action in self.ACTIONS, action |
|
191 |
if self.get_rqlexprs(action): |
|
192 |
return True |
|
193 |
if action in ('update', 'delete'): |
|
194 |
return self.has_group(action, 'owners') |
|
195 |
return False |
|
196 |
ERSchema.has_local_role = ERSchema_has_local_role |
|
197 |
||
198 |
||
199 |
def system_etypes(schema): |
|
200 |
"""return system entity types only: skip final, schema and application entities |
|
201 |
""" |
|
202 |
for eschema in schema.entities(): |
|
2126
a25859917ccc
stop using meta attribute from yams schema. Use instead sets defining meta relations and another defining schema types. Refactor various schema view based on this
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
203 |
if eschema.is_final() or eschema.schema_entity(): |
0 | 204 |
continue |
205 |
yield eschema.type |
|
206 |
||
207 |
# Schema objects definition ################################################### |
|
208 |
||
209 |
class CubicWebEntitySchema(EntitySchema): |
|
210 |
"""a entity has a type, a set of subject and or object relations |
|
211 |
the entity schema defines the possible relations for a given type and some |
|
212 |
constraints on those relations |
|
213 |
""" |
|
214 |
def __init__(self, schema=None, edef=None, eid=None, **kwargs): |
|
215 |
super(CubicWebEntitySchema, self).__init__(schema, edef, **kwargs) |
|
216 |
if eid is None and edef is not None: |
|
217 |
eid = getattr(edef, 'eid', None) |
|
218 |
self.eid = eid |
|
219 |
# take care: no _groups attribute when deep-copying |
|
1451 | 220 |
if getattr(self, '_groups', None): |
0 | 221 |
for groups in self._groups.itervalues(): |
222 |
for group_or_rqlexpr in groups: |
|
223 |
if isinstance(group_or_rqlexpr, RRQLExpression): |
|
224 |
msg = "can't use RRQLExpression on an entity type, use an ERQLExpression (%s)" |
|
225 |
raise BadSchemaDefinition(msg % self.type) |
|
1451 | 226 |
|
0 | 227 |
def attribute_definitions(self): |
228 |
"""return an iterator on attribute definitions |
|
1451 | 229 |
|
0 | 230 |
attribute relations are a subset of subject relations where the |
231 |
object's type is a final entity |
|
1451 | 232 |
|
0 | 233 |
an attribute definition is a 2-uple : |
234 |
* name of the relation |
|
235 |
* schema of the destination entity type |
|
236 |
""" |
|
237 |
iter = super(CubicWebEntitySchema, self).attribute_definitions() |
|
238 |
for rschema, attrschema in iter: |
|
239 |
if rschema.type == 'has_text': |
|
240 |
continue |
|
241 |
yield rschema, attrschema |
|
1451 | 242 |
|
2128
464edb198faa
drop @ wildcard in relation subject/object, override main_attribute for proper behaviour
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2126
diff
changeset
|
243 |
def main_attribute(self): |
464edb198faa
drop @ wildcard in relation subject/object, override main_attribute for proper behaviour
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2126
diff
changeset
|
244 |
"""convenience method that returns the *main* (i.e. the first non meta) |
464edb198faa
drop @ wildcard in relation subject/object, override main_attribute for proper behaviour
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2126
diff
changeset
|
245 |
attribute defined in the entity schema |
464edb198faa
drop @ wildcard in relation subject/object, override main_attribute for proper behaviour
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2126
diff
changeset
|
246 |
""" |
464edb198faa
drop @ wildcard in relation subject/object, override main_attribute for proper behaviour
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2126
diff
changeset
|
247 |
for rschema, _ in self.attribute_definitions(): |
2622
3c7edaa6c6d2
oops, should have been in a earlier commit (META_RELATION_TYPES renaming)
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2616
diff
changeset
|
248 |
if not (rschema in META_RTYPES |
2128
464edb198faa
drop @ wildcard in relation subject/object, override main_attribute for proper behaviour
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2126
diff
changeset
|
249 |
or self.is_metadata(rschema)): |
464edb198faa
drop @ wildcard in relation subject/object, override main_attribute for proper behaviour
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2126
diff
changeset
|
250 |
return rschema |
464edb198faa
drop @ wildcard in relation subject/object, override main_attribute for proper behaviour
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2126
diff
changeset
|
251 |
|
0 | 252 |
def add_subject_relation(self, rschema): |
253 |
"""register the relation schema as possible subject relation""" |
|
254 |
super(CubicWebEntitySchema, self).add_subject_relation(rschema) |
|
255 |
self._update_has_text() |
|
256 |
||
257 |
def del_subject_relation(self, rtype): |
|
258 |
super(CubicWebEntitySchema, self).del_subject_relation(rtype) |
|
2632
920bfaff60a4
B [schema update] may remove has_text unexpectedly, give another argument to fix it
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2622
diff
changeset
|
259 |
self._update_has_text(True) |
1451 | 260 |
|
2632
920bfaff60a4
B [schema update] may remove has_text unexpectedly, give another argument to fix it
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2622
diff
changeset
|
261 |
def _update_has_text(self, deletion=False): |
0 | 262 |
may_need_has_text, has_has_text = False, False |
2632
920bfaff60a4
B [schema update] may remove has_text unexpectedly, give another argument to fix it
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2622
diff
changeset
|
263 |
need_has_text = None |
0 | 264 |
for rschema in self.subject_relations(): |
265 |
if rschema.is_final(): |
|
266 |
if rschema == 'has_text': |
|
267 |
has_has_text = True |
|
268 |
elif self.rproperty(rschema, 'fulltextindexed'): |
|
269 |
may_need_has_text = True |
|
270 |
elif rschema.fulltext_container: |
|
271 |
if rschema.fulltext_container == 'subject': |
|
272 |
may_need_has_text = True |
|
273 |
else: |
|
274 |
need_has_text = False |
|
275 |
for rschema in self.object_relations(): |
|
276 |
if rschema.fulltext_container: |
|
277 |
if rschema.fulltext_container == 'object': |
|
278 |
may_need_has_text = True |
|
279 |
else: |
|
280 |
need_has_text = False |
|
281 |
if need_has_text is None: |
|
282 |
need_has_text = may_need_has_text |
|
2632
920bfaff60a4
B [schema update] may remove has_text unexpectedly, give another argument to fix it
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2622
diff
changeset
|
283 |
if need_has_text and not has_has_text and not deletion: |
0 | 284 |
rdef = ybo.RelationDefinition(self.type, 'has_text', 'String') |
285 |
self.schema.add_relation_def(rdef) |
|
286 |
elif not need_has_text and has_has_text: |
|
287 |
self.schema.del_relation_def(self.type, 'has_text', 'String') |
|
1451 | 288 |
|
0 | 289 |
def schema_entity(self): |
290 |
"""return True if this entity type is used to build the schema""" |
|
2126
a25859917ccc
stop using meta attribute from yams schema. Use instead sets defining meta relations and another defining schema types. Refactor various schema view based on this
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
291 |
return self.type in SCHEMA_TYPES |
0 | 292 |
|
293 |
def check_perm(self, session, action, eid=None): |
|
294 |
# NB: session may be a server session or a request object |
|
295 |
user = session.user |
|
296 |
# check user is in an allowed group, if so that's enough |
|
297 |
# internal sessions should always stop there |
|
298 |
if user.matching_groups(self.get_groups(action)): |
|
299 |
return |
|
300 |
# if 'owners' in allowed groups, check if the user actually owns this |
|
301 |
# object, if so that's enough |
|
302 |
if eid is not None and 'owners' in self.get_groups(action) and \ |
|
303 |
user.owns(eid): |
|
304 |
return |
|
305 |
# else if there is some rql expressions, check them |
|
306 |
if any(rqlexpr.check(session, eid) |
|
307 |
for rqlexpr in self.get_rqlexprs(action)): |
|
1451 | 308 |
return |
0 | 309 |
raise Unauthorized(action, str(self)) |
310 |
||
311 |
def rql_expression(self, expression, mainvars=None, eid=None): |
|
312 |
"""rql expression factory""" |
|
313 |
return ERQLExpression(expression, mainvars, eid) |
|
1451 | 314 |
|
2252 | 315 |
|
0 | 316 |
class CubicWebRelationSchema(RelationSchema): |
317 |
RelationSchema._RPROPERTIES['eid'] = None |
|
318 |
_perms_checked = False |
|
1451 | 319 |
|
0 | 320 |
def __init__(self, schema=None, rdef=None, eid=None, **kwargs): |
321 |
if rdef is not None: |
|
322 |
# if this relation is inlined |
|
323 |
self.inlined = rdef.inlined |
|
324 |
super(CubicWebRelationSchema, self).__init__(schema, rdef, **kwargs) |
|
325 |
if eid is None and rdef is not None: |
|
326 |
eid = getattr(rdef, 'eid', None) |
|
327 |
self.eid = eid |
|
1451 | 328 |
|
2126
a25859917ccc
stop using meta attribute from yams schema. Use instead sets defining meta relations and another defining schema types. Refactor various schema view based on this
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
329 |
@property |
a25859917ccc
stop using meta attribute from yams schema. Use instead sets defining meta relations and another defining schema types. Refactor various schema view based on this
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
330 |
def meta(self): |
2622
3c7edaa6c6d2
oops, should have been in a earlier commit (META_RELATION_TYPES renaming)
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2616
diff
changeset
|
331 |
return self.type in META_RTYPES |
1451 | 332 |
|
0 | 333 |
def update(self, subjschema, objschema, rdef): |
334 |
super(CubicWebRelationSchema, self).update(subjschema, objschema, rdef) |
|
335 |
if not self._perms_checked and self._groups: |
|
336 |
for action, groups in self._groups.iteritems(): |
|
337 |
for group_or_rqlexpr in groups: |
|
338 |
if action == 'read' and \ |
|
339 |
isinstance(group_or_rqlexpr, RQLExpression): |
|
340 |
msg = "can't use rql expression for read permission of "\ |
|
341 |
"a relation type (%s)" |
|
342 |
raise BadSchemaDefinition(msg % self.type) |
|
343 |
elif self.final and isinstance(group_or_rqlexpr, RRQLExpression): |
|
344 |
if self.schema.reading_from_database: |
|
345 |
# we didn't have final relation earlier, so turn |
|
346 |
# RRQLExpression into ERQLExpression now |
|
347 |
rqlexpr = group_or_rqlexpr |
|
348 |
newrqlexprs = [x for x in self.get_rqlexprs(action) if not x is rqlexpr] |
|
349 |
newrqlexprs.append(ERQLExpression(rqlexpr.expression, |
|
350 |
rqlexpr.mainvars, |
|
351 |
rqlexpr.eid)) |
|
1451 | 352 |
self.set_rqlexprs(action, newrqlexprs) |
0 | 353 |
else: |
354 |
msg = "can't use RRQLExpression on a final relation "\ |
|
355 |
"type (eg attribute relation), use an ERQLExpression (%s)" |
|
356 |
raise BadSchemaDefinition(msg % self.type) |
|
357 |
elif not self.final and \ |
|
358 |
isinstance(group_or_rqlexpr, ERQLExpression): |
|
359 |
msg = "can't use ERQLExpression on a relation type, use "\ |
|
360 |
"a RRQLExpression (%s)" |
|
361 |
raise BadSchemaDefinition(msg % self.type) |
|
362 |
self._perms_checked = True |
|
1451 | 363 |
|
0 | 364 |
def cardinality(self, subjtype, objtype, target): |
365 |
card = self.rproperty(subjtype, objtype, 'cardinality') |
|
366 |
return (target == 'subject' and card[0]) or \ |
|
367 |
(target == 'object' and card[1]) |
|
1451 | 368 |
|
0 | 369 |
def schema_relation(self): |
2126
a25859917ccc
stop using meta attribute from yams schema. Use instead sets defining meta relations and another defining schema types. Refactor various schema view based on this
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
370 |
"""return True if this relation type is used to build the schema""" |
a25859917ccc
stop using meta attribute from yams schema. Use instead sets defining meta relations and another defining schema types. Refactor various schema view based on this
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
371 |
return self.type in SCHEMA_TYPES |
1451 | 372 |
|
0 | 373 |
def physical_mode(self): |
374 |
"""return an appropriate mode for physical storage of this relation type: |
|
375 |
* 'subjectinline' if every possible subject cardinalities are 1 or ? |
|
376 |
* 'objectinline' if 'subjectinline' mode is not possible but every |
|
377 |
possible object cardinalities are 1 or ? |
|
378 |
* None if neither 'subjectinline' and 'objectinline' |
|
379 |
""" |
|
380 |
assert not self.final |
|
381 |
return self.inlined and 'subjectinline' or None |
|
382 |
||
383 |
def check_perm(self, session, action, *args, **kwargs): |
|
384 |
# NB: session may be a server session or a request object check user is |
|
385 |
# in an allowed group, if so that's enough internal sessions should |
|
386 |
# always stop there |
|
387 |
if session.user.matching_groups(self.get_groups(action)): |
|
1451 | 388 |
return |
0 | 389 |
# else if there is some rql expressions, check them |
390 |
if any(rqlexpr.check(session, *args, **kwargs) |
|
391 |
for rqlexpr in self.get_rqlexprs(action)): |
|
392 |
return |
|
393 |
raise Unauthorized(action, str(self)) |
|
394 |
||
395 |
def rql_expression(self, expression, mainvars=None, eid=None): |
|
396 |
"""rql expression factory""" |
|
397 |
if self.is_final(): |
|
398 |
return ERQLExpression(expression, mainvars, eid) |
|
399 |
return RRQLExpression(expression, mainvars, eid) |
|
400 |
||
1451 | 401 |
|
0 | 402 |
class CubicWebSchema(Schema): |
403 |
"""set of entities and relations schema defining the possible data sets |
|
404 |
used in an application |
|
405 |
||
406 |
||
407 |
:type name: str |
|
2476
1294a6bdf3bf
application -> instance where it makes sense
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2460
diff
changeset
|
408 |
:ivar name: name of the schema, usually the instance identifier |
1451 | 409 |
|
0 | 410 |
:type base: str |
411 |
:ivar base: path of the directory where the schema is defined |
|
412 |
""" |
|
1451 | 413 |
reading_from_database = False |
0 | 414 |
entity_class = CubicWebEntitySchema |
415 |
relation_class = CubicWebRelationSchema |
|
416 |
||
417 |
def __init__(self, *args, **kwargs): |
|
418 |
self._eid_index = {} |
|
419 |
super(CubicWebSchema, self).__init__(*args, **kwargs) |
|
420 |
ybo.register_base_types(self) |
|
2300
c8151d004e06
meta has been drop
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2293
diff
changeset
|
421 |
rschema = self.add_relation_type(ybo.RelationType('eid')) |
0 | 422 |
rschema.final = True |
423 |
rschema.set_default_groups() |
|
2300
c8151d004e06
meta has been drop
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2293
diff
changeset
|
424 |
rschema = self.add_relation_type(ybo.RelationType('has_text')) |
0 | 425 |
rschema.final = True |
426 |
rschema.set_default_groups() |
|
2300
c8151d004e06
meta has been drop
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2293
diff
changeset
|
427 |
rschema = self.add_relation_type(ybo.RelationType('identity')) |
0 | 428 |
rschema.final = False |
429 |
rschema.set_default_groups() |
|
1451 | 430 |
|
0 | 431 |
def add_entity_type(self, edef): |
432 |
edef.name = edef.name.encode() |
|
433 |
edef.name = bw_normalize_etype(edef.name) |
|
434 |
assert re.match(r'[A-Z][A-Za-z0-9]*[a-z]+[0-9]*$', edef.name), repr(edef.name) |
|
435 |
eschema = super(CubicWebSchema, self).add_entity_type(edef) |
|
436 |
if not eschema.is_final(): |
|
437 |
# automatically add the eid relation to non final entity types |
|
438 |
rdef = ybo.RelationDefinition(eschema.type, 'eid', 'Int', |
|
439 |
cardinality='11', uid=True) |
|
440 |
self.add_relation_def(rdef) |
|
441 |
rdef = ybo.RelationDefinition(eschema.type, 'identity', eschema.type) |
|
442 |
self.add_relation_def(rdef) |
|
443 |
self._eid_index[eschema.eid] = eschema |
|
444 |
return eschema |
|
1451 | 445 |
|
0 | 446 |
def add_relation_type(self, rdef): |
447 |
rdef.name = rdef.name.lower().encode() |
|
448 |
rschema = super(CubicWebSchema, self).add_relation_type(rdef) |
|
449 |
self._eid_index[rschema.eid] = rschema |
|
450 |
return rschema |
|
1451 | 451 |
|
0 | 452 |
def add_relation_def(self, rdef): |
453 |
"""build a part of a relation schema |
|
454 |
(i.e. add a relation between two specific entity's types) |
|
455 |
||
456 |
:type subject: str |
|
457 |
:param subject: entity's type that is subject of the relation |
|
458 |
||
459 |
:type rtype: str |
|
460 |
:param rtype: the relation's type (i.e. the name of the relation) |
|
461 |
||
462 |
:type obj: str |
|
463 |
:param obj: entity's type that is object of the relation |
|
464 |
||
465 |
:rtype: RelationSchema |
|
466 |
:param: the newly created or just completed relation schema |
|
467 |
""" |
|
468 |
rdef.name = rdef.name.lower() |
|
469 |
rdef.subject = bw_normalize_etype(rdef.subject) |
|
470 |
rdef.object = bw_normalize_etype(rdef.object) |
|
1034
0356bbfb2f26
fix to pass arguments to base class
sylvain.thenault@logilab.fr
parents:
1016
diff
changeset
|
471 |
if super(CubicWebSchema, self).add_relation_def(rdef): |
0356bbfb2f26
fix to pass arguments to base class
sylvain.thenault@logilab.fr
parents:
1016
diff
changeset
|
472 |
try: |
0356bbfb2f26
fix to pass arguments to base class
sylvain.thenault@logilab.fr
parents:
1016
diff
changeset
|
473 |
self._eid_index[rdef.eid] = (self.eschema(rdef.subject), |
0356bbfb2f26
fix to pass arguments to base class
sylvain.thenault@logilab.fr
parents:
1016
diff
changeset
|
474 |
self.rschema(rdef.name), |
0356bbfb2f26
fix to pass arguments to base class
sylvain.thenault@logilab.fr
parents:
1016
diff
changeset
|
475 |
self.eschema(rdef.object)) |
0356bbfb2f26
fix to pass arguments to base class
sylvain.thenault@logilab.fr
parents:
1016
diff
changeset
|
476 |
except AttributeError: |
0356bbfb2f26
fix to pass arguments to base class
sylvain.thenault@logilab.fr
parents:
1016
diff
changeset
|
477 |
pass # not a serialized schema |
1451 | 478 |
|
0 | 479 |
def del_relation_type(self, rtype): |
480 |
rschema = self.rschema(rtype) |
|
481 |
self._eid_index.pop(rschema.eid, None) |
|
482 |
super(CubicWebSchema, self).del_relation_type(rtype) |
|
1451 | 483 |
|
0 | 484 |
def del_relation_def(self, subjtype, rtype, objtype): |
485 |
for k, v in self._eid_index.items(): |
|
486 |
if v == (subjtype, rtype, objtype): |
|
487 |
del self._eid_index[k] |
|
488 |
super(CubicWebSchema, self).del_relation_def(subjtype, rtype, objtype) |
|
1451 | 489 |
|
0 | 490 |
def del_entity_type(self, etype): |
491 |
eschema = self.eschema(etype) |
|
492 |
self._eid_index.pop(eschema.eid, None) |
|
493 |
# deal with has_text first, else its automatic deletion (see above) |
|
494 |
# may trigger an error in ancestor's del_entity_type method |
|
495 |
if 'has_text' in eschema.subject_relations(): |
|
496 |
self.del_relation_def(etype, 'has_text', 'String') |
|
497 |
super(CubicWebSchema, self).del_entity_type(etype) |
|
1451 | 498 |
|
0 | 499 |
def schema_by_eid(self, eid): |
500 |
return self._eid_index[eid] |
|
501 |
||
502 |
||
503 |
# Possible constraints ######################################################## |
|
504 |
||
505 |
class RQLVocabularyConstraint(BaseConstraint): |
|
506 |
"""the rql vocabulary constraint : |
|
507 |
||
508 |
limit the proposed values to a set of entities returned by a rql query, |
|
509 |
but this is not enforced at the repository level |
|
1451 | 510 |
|
0 | 511 |
restriction is additional rql restriction that will be added to |
512 |
a predefined query, where the S and O variables respectivly represent |
|
513 |
the subject and the object of the relation |
|
514 |
""" |
|
1451 | 515 |
|
0 | 516 |
def __init__(self, restriction): |
517 |
self.restriction = restriction |
|
518 |
||
2691
ade319674170
add consistency check on constraints
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2632
diff
changeset
|
519 |
def check_consistency(self, subjschema, objschema): |
ade319674170
add consistency check on constraints
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2632
diff
changeset
|
520 |
if objschema.is_final(): |
ade319674170
add consistency check on constraints
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2632
diff
changeset
|
521 |
raise BadSchemaDefinition("unique constraint doesn't apply to " |
ade319674170
add consistency check on constraints
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2632
diff
changeset
|
522 |
"final entity type") |
ade319674170
add consistency check on constraints
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2632
diff
changeset
|
523 |
|
0 | 524 |
def serialize(self): |
525 |
return self.restriction |
|
1451 | 526 |
|
0 | 527 |
def deserialize(cls, value): |
528 |
return cls(value) |
|
529 |
deserialize = classmethod(deserialize) |
|
1451 | 530 |
|
0 | 531 |
def check(self, entity, rtype, value): |
532 |
"""return true if the value satisfy the constraint, else false""" |
|
533 |
# implemented as a hook in the repository |
|
534 |
return 1 |
|
535 |
||
536 |
def repo_check(self, session, eidfrom, rtype, eidto): |
|
537 |
"""raise ValidationError if the relation doesn't satisfy the constraint |
|
538 |
""" |
|
539 |
pass # this is a vocabulary constraint, not enforce |
|
1451 | 540 |
|
0 | 541 |
def __str__(self): |
542 |
return self.restriction |
|
543 |
||
544 |
def __repr__(self): |
|
545 |
return '<%s : %s>' % (self.__class__.__name__, repr(self.restriction)) |
|
546 |
||
547 |
||
548 |
class RQLConstraint(RQLVocabularyConstraint): |
|
549 |
"""the rql constraint is similar to the RQLVocabularyConstraint but |
|
550 |
are also enforced at the repository level |
|
551 |
""" |
|
552 |
def exec_query(self, session, eidfrom, eidto): |
|
553 |
rql = 'Any S,O WHERE S eid %(s)s, O eid %(o)s, ' + self.restriction |
|
554 |
return session.unsafe_execute(rql, {'s': eidfrom, 'o': eidto}, |
|
555 |
('s', 'o'), build_descr=False) |
|
556 |
def error(self, eid, rtype, msg): |
|
557 |
raise ValidationError(eid, {rtype: msg}) |
|
1451 | 558 |
|
0 | 559 |
def repo_check(self, session, eidfrom, rtype, eidto): |
560 |
"""raise ValidationError if the relation doesn't satisfy the constraint |
|
561 |
""" |
|
562 |
if not self.exec_query(session, eidfrom, eidto): |
|
563 |
# XXX at this point dunno if the validation error `occured` on |
|
564 |
# eidfrom or eidto (from user interface point of view) |
|
565 |
self.error(eidfrom, rtype, 'constraint %s failed' % self) |
|
566 |
||
567 |
||
568 |
class RQLUniqueConstraint(RQLConstraint): |
|
569 |
"""the unique rql constraint check that the result of the query isn't |
|
570 |
greater than one |
|
571 |
""" |
|
572 |
def repo_check(self, session, eidfrom, rtype, eidto): |
|
573 |
"""raise ValidationError if the relation doesn't satisfy the constraint |
|
574 |
""" |
|
575 |
if len(self.exec_query(session, eidfrom, eidto)) > 1: |
|
576 |
# XXX at this point dunno if the validation error `occured` on |
|
577 |
# eidfrom or eidto (from user interface point of view) |
|
578 |
self.error(eidfrom, rtype, 'unique constraint %s failed' % self) |
|
579 |
||
1451 | 580 |
|
0 | 581 |
def split_expression(rqlstring): |
582 |
for expr in rqlstring.split(','): |
|
583 |
for word in expr.split(): |
|
584 |
yield word |
|
1451 | 585 |
|
0 | 586 |
def normalize_expression(rqlstring): |
587 |
"""normalize an rql expression to ease schema synchronization (avoid |
|
588 |
suppressing and reinserting an expression if only a space has been added/removed |
|
589 |
for instance) |
|
590 |
""" |
|
591 |
return u', '.join(' '.join(expr.split()) for expr in rqlstring.split(',')) |
|
592 |
||
593 |
||
594 |
class RQLExpression(object): |
|
595 |
def __init__(self, expression, mainvars, eid): |
|
596 |
self.eid = eid # eid of the entity representing this rql expression |
|
597 |
if not isinstance(mainvars, unicode): |
|
598 |
mainvars = unicode(mainvars) |
|
599 |
self.mainvars = mainvars |
|
600 |
self.expression = normalize_expression(expression) |
|
601 |
try: |
|
602 |
self.rqlst = parse(self.full_rql, print_errors=False).children[0] |
|
603 |
except RQLSyntaxError: |
|
604 |
raise RQLSyntaxError(expression) |
|
605 |
for mainvar in mainvars.split(','): |
|
606 |
if len(self.rqlst.defined_vars[mainvar].references()) <= 2: |
|
2142
098aa2075903
include_schema_files is useless
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
607 |
_LOGGER.warn('You did not use the %s variable in your RQL ' |
098aa2075903
include_schema_files is useless
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
608 |
'expression %s', mainvar, self) |
1451 | 609 |
|
0 | 610 |
def __str__(self): |
611 |
return self.full_rql |
|
612 |
def __repr__(self): |
|
613 |
return '%s(%s)' % (self.__class__.__name__, self.full_rql) |
|
1451 | 614 |
|
0 | 615 |
def __deepcopy__(self, memo): |
616 |
return self.__class__(self.expression, self.mainvars) |
|
617 |
def __getstate__(self): |
|
618 |
return (self.expression, self.mainvars) |
|
619 |
def __setstate__(self, state): |
|
620 |
self.__init__(*state) |
|
1451 | 621 |
|
0 | 622 |
@cached |
623 |
def transform_has_permission(self): |
|
624 |
found = None |
|
625 |
rqlst = self.rqlst |
|
626 |
for var in rqlst.defined_vars.itervalues(): |
|
627 |
for varref in var.references(): |
|
628 |
rel = varref.relation() |
|
629 |
if rel is None: |
|
630 |
continue |
|
631 |
try: |
|
632 |
prefix, action, suffix = rel.r_type.split('_') |
|
633 |
except ValueError: |
|
634 |
continue |
|
635 |
if prefix != 'has' or suffix != 'permission' or \ |
|
636 |
not action in ('add', 'delete', 'update', 'read'): |
|
637 |
continue |
|
638 |
if found is None: |
|
639 |
found = [] |
|
640 |
rqlst.save_state() |
|
641 |
assert rel.children[0].name == 'U' |
|
642 |
objvar = rel.children[1].children[0].variable |
|
643 |
rqlst.remove_node(rel) |
|
644 |
selected = [v.name for v in rqlst.get_selected_variables()] |
|
645 |
if objvar.name not in selected: |
|
646 |
colindex = len(selected) |
|
647 |
rqlst.add_selected(objvar) |
|
648 |
else: |
|
649 |
colindex = selected.index(objvar.name) |
|
650 |
found.append((action, objvar, colindex)) |
|
651 |
# remove U eid %(u)s if U is not used in any other relation |
|
652 |
uvrefs = rqlst.defined_vars['U'].references() |
|
653 |
if len(uvrefs) == 1: |
|
654 |
rqlst.remove_node(uvrefs[0].relation()) |
|
655 |
if found is not None: |
|
656 |
rql = rqlst.as_string() |
|
657 |
if len(rqlst.selection) == 1 and isinstance(rqlst.where, nodes.Relation): |
|
658 |
# only "Any X WHERE X eid %(x)s" remaining, no need to execute the rql |
|
659 |
keyarg = rqlst.selection[0].name.lower() |
|
660 |
else: |
|
661 |
keyarg = None |
|
662 |
rqlst.recover() |
|
663 |
return rql, found, keyarg |
|
664 |
return rqlst.as_string(), None, None |
|
1451 | 665 |
|
0 | 666 |
def _check(self, session, **kwargs): |
667 |
"""return True if the rql expression is matching the given relation |
|
668 |
between fromeid and toeid |
|
669 |
||
670 |
session may actually be a request as well |
|
671 |
""" |
|
672 |
if self.eid is not None: |
|
673 |
key = (self.eid, tuple(sorted(kwargs.iteritems()))) |
|
674 |
try: |
|
675 |
return session.local_perm_cache[key] |
|
676 |
except KeyError: |
|
677 |
pass |
|
678 |
rql, has_perm_defs, keyarg = self.transform_has_permission() |
|
679 |
if keyarg is None: |
|
680 |
# on the server side, use unsafe_execute, but this is not available |
|
681 |
# on the client side (session is actually a request) |
|
682 |
execute = getattr(session, 'unsafe_execute', session.execute) |
|
683 |
# XXX what if 'u' in kwargs |
|
684 |
cachekey = kwargs.keys() |
|
685 |
kwargs['u'] = session.user.eid |
|
686 |
try: |
|
687 |
rset = execute(rql, kwargs, cachekey, build_descr=True) |
|
688 |
except NotImplementedError: |
|
689 |
self.critical('cant check rql expression, unsupported rql %s', rql) |
|
690 |
if self.eid is not None: |
|
691 |
session.local_perm_cache[key] = False |
|
692 |
return False |
|
693 |
except TypeResolverException, ex: |
|
694 |
# some expression may not be resolvable with current kwargs |
|
695 |
# (type conflict) |
|
696 |
self.warning('%s: %s', rql, str(ex)) |
|
697 |
if self.eid is not None: |
|
698 |
session.local_perm_cache[key] = False |
|
699 |
return False |
|
700 |
else: |
|
701 |
rset = session.eid_rset(kwargs[keyarg]) |
|
702 |
# if no special has_*_permission relation in the rql expression, just |
|
703 |
# check the result set contains something |
|
704 |
if has_perm_defs is None: |
|
705 |
if rset: |
|
706 |
if self.eid is not None: |
|
707 |
session.local_perm_cache[key] = True |
|
708 |
return True |
|
709 |
elif rset: |
|
710 |
# check every special has_*_permission relation is satisfied |
|
711 |
get_eschema = session.vreg.schema.eschema |
|
712 |
try: |
|
713 |
for eaction, var, col in has_perm_defs: |
|
714 |
for i in xrange(len(rset)): |
|
715 |
eschema = get_eschema(rset.description[i][col]) |
|
716 |
eschema.check_perm(session, eaction, rset[i][col]) |
|
717 |
if self.eid is not None: |
|
718 |
session.local_perm_cache[key] = True |
|
719 |
return True |
|
720 |
except Unauthorized: |
|
721 |
pass |
|
722 |
if self.eid is not None: |
|
723 |
session.local_perm_cache[key] = False |
|
724 |
return False |
|
1451 | 725 |
|
0 | 726 |
@property |
727 |
def minimal_rql(self): |
|
728 |
return 'Any %s WHERE %s' % (self.mainvars, self.expression) |
|
729 |
||
730 |
||
731 |
class ERQLExpression(RQLExpression): |
|
732 |
def __init__(self, expression, mainvars=None, eid=None): |
|
733 |
RQLExpression.__init__(self, expression, mainvars or 'X', eid) |
|
734 |
# syntax tree used by read security (inserted in queries when necessary |
|
735 |
self.snippet_rqlst = parse(self.minimal_rql, print_errors=False).children[0] |
|
736 |
||
737 |
@property |
|
738 |
def full_rql(self): |
|
739 |
rql = self.minimal_rql |
|
740 |
rqlst = getattr(self, 'rqlst', None) # may be not set yet |
|
741 |
if rqlst is not None: |
|
742 |
defined = rqlst.defined_vars |
|
743 |
else: |
|
744 |
defined = set(split_expression(self.expression)) |
|
745 |
if 'X' in defined: |
|
746 |
rql += ', X eid %(x)s' |
|
747 |
if 'U' in defined: |
|
748 |
rql += ', U eid %(u)s' |
|
749 |
return rql |
|
1451 | 750 |
|
0 | 751 |
def check(self, session, eid=None): |
752 |
if 'X' in self.rqlst.defined_vars: |
|
753 |
if eid is None: |
|
754 |
return False |
|
755 |
return self._check(session, x=eid) |
|
756 |
return self._check(session) |
|
1451 | 757 |
|
2301
a9e9582d5fb6
obsolete implicit context
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2300
diff
changeset
|
758 |
PyFileReader.context['ERQLExpression'] = yobsolete(ERQLExpression) |
1451 | 759 |
|
0 | 760 |
class RRQLExpression(RQLExpression): |
761 |
def __init__(self, expression, mainvars=None, eid=None): |
|
762 |
if mainvars is None: |
|
763 |
defined = set(split_expression(expression)) |
|
764 |
mainvars = [] |
|
765 |
if 'S' in defined: |
|
766 |
mainvars.append('S') |
|
767 |
if 'O' in defined: |
|
768 |
mainvars.append('O') |
|
769 |
if not mainvars: |
|
770 |
raise Exception('unable to guess selection variables') |
|
771 |
mainvars = ','.join(mainvars) |
|
772 |
RQLExpression.__init__(self, expression, mainvars, eid) |
|
773 |
||
774 |
@property |
|
775 |
def full_rql(self): |
|
776 |
rql = self.minimal_rql |
|
777 |
rqlst = getattr(self, 'rqlst', None) # may be not set yet |
|
778 |
if rqlst is not None: |
|
779 |
defined = rqlst.defined_vars |
|
780 |
else: |
|
781 |
defined = set(split_expression(self.expression)) |
|
782 |
if 'S' in defined: |
|
783 |
rql += ', S eid %(s)s' |
|
784 |
if 'O' in defined: |
|
785 |
rql += ', O eid %(o)s' |
|
786 |
if 'U' in defined: |
|
787 |
rql += ', U eid %(u)s' |
|
788 |
return rql |
|
1451 | 789 |
|
0 | 790 |
def check(self, session, fromeid=None, toeid=None): |
791 |
kwargs = {} |
|
792 |
if 'S' in self.rqlst.defined_vars: |
|
793 |
if fromeid is None: |
|
794 |
return False |
|
795 |
kwargs['s'] = fromeid |
|
796 |
if 'O' in self.rqlst.defined_vars: |
|
797 |
if toeid is None: |
|
798 |
return False |
|
799 |
kwargs['o'] = toeid |
|
800 |
return self._check(session, **kwargs) |
|
1451 | 801 |
|
2301
a9e9582d5fb6
obsolete implicit context
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2300
diff
changeset
|
802 |
PyFileReader.context['RRQLExpression'] = yobsolete(RRQLExpression) |
0 | 803 |
|
629
59b6542f5729
provide a new WorkflowableEntityType base class (will be refactored later, maybe with schema interfaces)
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
628
diff
changeset
|
804 |
# workflow extensions ######################################################### |
2460
ce1a7ffc6c90
fix a couple NameErrors
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
2459
diff
changeset
|
805 |
from yams.buildobjs import _add_relation as yams_add_relation |
629
59b6542f5729
provide a new WorkflowableEntityType base class (will be refactored later, maybe with schema interfaces)
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
628
diff
changeset
|
806 |
|
59b6542f5729
provide a new WorkflowableEntityType base class (will be refactored later, maybe with schema interfaces)
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
628
diff
changeset
|
807 |
class workflowable_definition(ybo.metadefinition): |
59b6542f5729
provide a new WorkflowableEntityType base class (will be refactored later, maybe with schema interfaces)
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
628
diff
changeset
|
808 |
"""extends default EntityType's metaclass to add workflow relations |
59b6542f5729
provide a new WorkflowableEntityType base class (will be refactored later, maybe with schema interfaces)
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
628
diff
changeset
|
809 |
(i.e. in_state and wf_info_for). |
59b6542f5729
provide a new WorkflowableEntityType base class (will be refactored later, maybe with schema interfaces)
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
628
diff
changeset
|
810 |
This is the default metaclass for WorkflowableEntityType |
59b6542f5729
provide a new WorkflowableEntityType base class (will be refactored later, maybe with schema interfaces)
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
628
diff
changeset
|
811 |
""" |
59b6542f5729
provide a new WorkflowableEntityType base class (will be refactored later, maybe with schema interfaces)
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
628
diff
changeset
|
812 |
def __new__(mcs, name, bases, classdict): |
59b6542f5729
provide a new WorkflowableEntityType base class (will be refactored later, maybe with schema interfaces)
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
628
diff
changeset
|
813 |
abstract = classdict.pop('abstract', False) |
59b6542f5729
provide a new WorkflowableEntityType base class (will be refactored later, maybe with schema interfaces)
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
628
diff
changeset
|
814 |
defclass = super(workflowable_definition, mcs).__new__(mcs, name, bases, classdict) |
59b6542f5729
provide a new WorkflowableEntityType base class (will be refactored later, maybe with schema interfaces)
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
628
diff
changeset
|
815 |
if not abstract: |
59b6542f5729
provide a new WorkflowableEntityType base class (will be refactored later, maybe with schema interfaces)
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
628
diff
changeset
|
816 |
existing_rels = set(rdef.name for rdef in defclass.__relations__) |
59b6542f5729
provide a new WorkflowableEntityType base class (will be refactored later, maybe with schema interfaces)
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
628
diff
changeset
|
817 |
if 'in_state' not in existing_rels and 'wf_info_for' not in existing_rels: |
59b6542f5729
provide a new WorkflowableEntityType base class (will be refactored later, maybe with schema interfaces)
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
628
diff
changeset
|
818 |
in_state = ybo.SubjectRelation('State', cardinality='1*', |
59b6542f5729
provide a new WorkflowableEntityType base class (will be refactored later, maybe with schema interfaces)
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
628
diff
changeset
|
819 |
# XXX automatize this |
59b6542f5729
provide a new WorkflowableEntityType base class (will be refactored later, maybe with schema interfaces)
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
628
diff
changeset
|
820 |
constraints=[RQLConstraint('S is ET, O state_of ET')], |
59b6542f5729
provide a new WorkflowableEntityType base class (will be refactored later, maybe with schema interfaces)
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
628
diff
changeset
|
821 |
description=_('account state')) |
59b6542f5729
provide a new WorkflowableEntityType base class (will be refactored later, maybe with schema interfaces)
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
628
diff
changeset
|
822 |
yams_add_relation(defclass.__relations__, in_state, 'in_state') |
59b6542f5729
provide a new WorkflowableEntityType base class (will be refactored later, maybe with schema interfaces)
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
628
diff
changeset
|
823 |
wf_info_for = ybo.ObjectRelation('TrInfo', cardinality='1*', composite='object') |
59b6542f5729
provide a new WorkflowableEntityType base class (will be refactored later, maybe with schema interfaces)
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
628
diff
changeset
|
824 |
yams_add_relation(defclass.__relations__, wf_info_for, 'wf_info_for') |
59b6542f5729
provide a new WorkflowableEntityType base class (will be refactored later, maybe with schema interfaces)
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
628
diff
changeset
|
825 |
return defclass |
59b6542f5729
provide a new WorkflowableEntityType base class (will be refactored later, maybe with schema interfaces)
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
628
diff
changeset
|
826 |
|
59b6542f5729
provide a new WorkflowableEntityType base class (will be refactored later, maybe with schema interfaces)
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
628
diff
changeset
|
827 |
class WorkflowableEntityType(ybo.EntityType): |
59b6542f5729
provide a new WorkflowableEntityType base class (will be refactored later, maybe with schema interfaces)
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
628
diff
changeset
|
828 |
__metaclass__ = workflowable_definition |
59b6542f5729
provide a new WorkflowableEntityType base class (will be refactored later, maybe with schema interfaces)
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
628
diff
changeset
|
829 |
abstract = True |
1451 | 830 |
|
629
59b6542f5729
provide a new WorkflowableEntityType base class (will be refactored later, maybe with schema interfaces)
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
628
diff
changeset
|
831 |
PyFileReader.context['WorkflowableEntityType'] = WorkflowableEntityType |
59b6542f5729
provide a new WorkflowableEntityType base class (will be refactored later, maybe with schema interfaces)
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
628
diff
changeset
|
832 |
|
0 | 833 |
# schema loading ############################################################## |
834 |
||
835 |
CONSTRAINTS['RQLConstraint'] = RQLConstraint |
|
836 |
CONSTRAINTS['RQLUniqueConstraint'] = RQLUniqueConstraint |
|
837 |
CONSTRAINTS['RQLVocabularyConstraint'] = RQLVocabularyConstraint |
|
838 |
PyFileReader.context.update(CONSTRAINTS) |
|
839 |
||
840 |
||
841 |
class BootstrapSchemaLoader(SchemaLoader): |
|
842 |
"""cubicweb specific schema loader, loading only schema necessary to read |
|
843 |
the persistent schema |
|
844 |
""" |
|
845 |
schemacls = CubicWebSchema |
|
846 |
||
1034
0356bbfb2f26
fix to pass arguments to base class
sylvain.thenault@logilab.fr
parents:
1016
diff
changeset
|
847 |
def load(self, config, path=(), **kwargs): |
0 | 848 |
"""return a Schema instance from the schema definition read |
849 |
from <directory> |
|
850 |
""" |
|
851 |
self.lib_directory = config.schemas_lib_dir() |
|
852 |
return super(BootstrapSchemaLoader, self).load( |
|
1034
0356bbfb2f26
fix to pass arguments to base class
sylvain.thenault@logilab.fr
parents:
1016
diff
changeset
|
853 |
path, config.appid, register_base_types=False, **kwargs) |
1451 | 854 |
|
0 | 855 |
def _load_definition_files(self, cubes=None): |
856 |
# bootstraping, ignore cubes |
|
2142
098aa2075903
include_schema_files is useless
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
857 |
filepath = join(self.lib_directory, 'bootstrap.py') |
098aa2075903
include_schema_files is useless
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
858 |
self.info('loading %s', filepath) |
098aa2075903
include_schema_files is useless
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
859 |
self.handle_file(filepath) |
1451 | 860 |
|
0 | 861 |
def unhandled_file(self, filepath): |
862 |
"""called when a file without handler associated has been found""" |
|
863 |
self.warning('ignoring file %r', filepath) |
|
864 |
||
865 |
||
866 |
class CubicWebSchemaLoader(BootstrapSchemaLoader): |
|
867 |
"""cubicweb specific schema loader, automatically adding metadata to the |
|
2476
1294a6bdf3bf
application -> instance where it makes sense
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2460
diff
changeset
|
868 |
instance's schema |
0 | 869 |
""" |
870 |
||
1034
0356bbfb2f26
fix to pass arguments to base class
sylvain.thenault@logilab.fr
parents:
1016
diff
changeset
|
871 |
def load(self, config, **kwargs): |
0 | 872 |
"""return a Schema instance from the schema definition read |
873 |
from <directory> |
|
874 |
""" |
|
875 |
self.info('loading %s schemas', ', '.join(config.cubes())) |
|
372
a8a975a88368
check apphome is not None
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
0
diff
changeset
|
876 |
if config.apphome: |
2598
a66fe74bd9fc
[R schema] dont give an iterator, it's a trap
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2596
diff
changeset
|
877 |
path = tuple(reversed([config.apphome] + config.cubes_path())) |
372
a8a975a88368
check apphome is not None
Sylvain Thenault <sylvain.thenault@logilab.fr>
parents:
0
diff
changeset
|
878 |
else: |
2598
a66fe74bd9fc
[R schema] dont give an iterator, it's a trap
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2596
diff
changeset
|
879 |
path = tuple(reversed(config.cubes_path())) |
2526
40e41eb34a7d
we've to call cleanup_sys_modules manually for proper schema modules cleanup
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2476
diff
changeset
|
880 |
try: |
40e41eb34a7d
we've to call cleanup_sys_modules manually for proper schema modules cleanup
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2476
diff
changeset
|
881 |
return super(CubicWebSchemaLoader, self).load(config, path=path, **kwargs) |
40e41eb34a7d
we've to call cleanup_sys_modules manually for proper schema modules cleanup
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2476
diff
changeset
|
882 |
finally: |
40e41eb34a7d
we've to call cleanup_sys_modules manually for proper schema modules cleanup
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2476
diff
changeset
|
883 |
# we've to cleanup modules imported from cubicweb.schemas as well |
40e41eb34a7d
we've to call cleanup_sys_modules manually for proper schema modules cleanup
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2476
diff
changeset
|
884 |
cleanup_sys_modules([self.lib_directory]) |
0 | 885 |
|
886 |
def _load_definition_files(self, cubes): |
|
2142
098aa2075903
include_schema_files is useless
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
887 |
for filepath in (join(self.lib_directory, 'bootstrap.py'), |
098aa2075903
include_schema_files is useless
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
888 |
join(self.lib_directory, 'base.py'), |
098aa2075903
include_schema_files is useless
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
889 |
join(self.lib_directory, 'workflow.py'), |
098aa2075903
include_schema_files is useless
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
890 |
join(self.lib_directory, 'Bookmark.py')): |
0 | 891 |
self.info('loading %s', filepath) |
892 |
self.handle_file(filepath) |
|
893 |
for cube in cubes: |
|
894 |
for filepath in self.get_schema_files(cube): |
|
895 |
self.info('loading %s', filepath) |
|
896 |
self.handle_file(filepath) |
|
897 |
||
898 |
||
2459
d088d0ff48a1
move RichString and co to yams, keeping only a small monkeypatch for cw-page-template here
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2456
diff
changeset
|
899 |
set_log_methods(CubicWebSchemaLoader, getLogger('cubicweb.schemaloader')) |
d088d0ff48a1
move RichString and co to yams, keeping only a small monkeypatch for cw-page-template here
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2456
diff
changeset
|
900 |
set_log_methods(BootstrapSchemaLoader, getLogger('cubicweb.bootstrapschemaloader')) |
d088d0ff48a1
move RichString and co to yams, keeping only a small monkeypatch for cw-page-template here
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2456
diff
changeset
|
901 |
set_log_methods(RQLExpression, getLogger('cubicweb.schema')) |
d088d0ff48a1
move RichString and co to yams, keeping only a small monkeypatch for cw-page-template here
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2456
diff
changeset
|
902 |
|
0 | 903 |
# _() is just there to add messages to the catalog, don't care about actual |
904 |
# translation |
|
905 |
PERM_USE_TEMPLATE_FORMAT = _('use_template_format') |
|
2459
d088d0ff48a1
move RichString and co to yams, keeping only a small monkeypatch for cw-page-template here
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2456
diff
changeset
|
906 |
NEED_PERM_FORMATS = [_('text/cubicweb-page-template')] |
0 | 907 |
|
2531
531ea4e7013e
[cleanup] nicer imports
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
2526
diff
changeset
|
908 |
@monkeypatch(FormatConstraint) |
2459
d088d0ff48a1
move RichString and co to yams, keeping only a small monkeypatch for cw-page-template here
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2456
diff
changeset
|
909 |
def vocabulary(self, entity=None, req=None): |
d088d0ff48a1
move RichString and co to yams, keeping only a small monkeypatch for cw-page-template here
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2456
diff
changeset
|
910 |
if req is None and entity is not None: |
d088d0ff48a1
move RichString and co to yams, keeping only a small monkeypatch for cw-page-template here
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2456
diff
changeset
|
911 |
req = entity.req |
d088d0ff48a1
move RichString and co to yams, keeping only a small monkeypatch for cw-page-template here
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2456
diff
changeset
|
912 |
if req is not None and req.user.has_permission(PERM_USE_TEMPLATE_FORMAT): |
d088d0ff48a1
move RichString and co to yams, keeping only a small monkeypatch for cw-page-template here
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2456
diff
changeset
|
913 |
return self.regular_formats + tuple(NEED_PERM_FORMATS) |
d088d0ff48a1
move RichString and co to yams, keeping only a small monkeypatch for cw-page-template here
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2456
diff
changeset
|
914 |
return self.regular_formats |
0 | 915 |
|
916 |
# XXX monkey patch PyFileReader.import_erschema until bw_normalize_etype is |
|
917 |
# necessary |
|
918 |
orig_import_erschema = PyFileReader.import_erschema |
|
919 |
def bw_import_erschema(self, ertype, schemamod=None, instantiate=True): |
|
920 |
return orig_import_erschema(self, bw_normalize_etype(ertype), schemamod, instantiate) |
|
921 |
PyFileReader.import_erschema = bw_import_erschema |
|
1451 | 922 |
|
0 | 923 |
# XXX itou for some Statement methods |
924 |
from rql import stmts |
|
925 |
orig_get_etype = stmts.ScopeNode.get_etype |
|
926 |
def bw_get_etype(self, name): |
|
927 |
return orig_get_etype(self, bw_normalize_etype(name)) |
|
928 |
stmts.ScopeNode.get_etype = bw_get_etype |
|
929 |
||
930 |
orig_add_main_variable_delete = stmts.Delete.add_main_variable |
|
931 |
def bw_add_main_variable_delete(self, etype, vref): |
|
932 |
return orig_add_main_variable_delete(self, bw_normalize_etype(etype), vref) |
|
933 |
stmts.Delete.add_main_variable = bw_add_main_variable_delete |
|
934 |
||
935 |
orig_add_main_variable_insert = stmts.Insert.add_main_variable |
|
936 |
def bw_add_main_variable_insert(self, etype, vref): |
|
937 |
return orig_add_main_variable_insert(self, bw_normalize_etype(etype), vref) |
|
938 |
stmts.Insert.add_main_variable = bw_add_main_variable_insert |
|
939 |
||
940 |
orig_set_statement_type = stmts.Select.set_statement_type |
|
941 |
def bw_set_statement_type(self, etype): |
|
942 |
return orig_set_statement_type(self, bw_normalize_etype(etype)) |
|
943 |
stmts.Select.set_statement_type = bw_set_statement_type |