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