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