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