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