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