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