author | Sylvain Thénault <sylvain.thenault@logilab.fr> |
Fri, 07 Aug 2009 12:51:56 +0200 | |
changeset 2729 | d3dbd135f319 |
parent 2718 | 3a56b87bb5d6 |
child 2730 | bb6fcb8c5d71 |
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] |
|
2718
3a56b87bb5d6
[schema] break when found
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2716
diff
changeset
|
488 |
break |
0 | 489 |
super(CubicWebSchema, self).del_relation_def(subjtype, rtype, objtype) |
1451 | 490 |
|
0 | 491 |
def del_entity_type(self, etype): |
492 |
eschema = self.eschema(etype) |
|
493 |
self._eid_index.pop(eschema.eid, None) |
|
494 |
# deal with has_text first, else its automatic deletion (see above) |
|
495 |
# may trigger an error in ancestor's del_entity_type method |
|
496 |
if 'has_text' in eschema.subject_relations(): |
|
497 |
self.del_relation_def(etype, 'has_text', 'String') |
|
498 |
super(CubicWebSchema, self).del_entity_type(etype) |
|
1451 | 499 |
|
0 | 500 |
def schema_by_eid(self, eid): |
501 |
return self._eid_index[eid] |
|
502 |
||
503 |
||
504 |
# Possible constraints ######################################################## |
|
505 |
||
506 |
class RQLVocabularyConstraint(BaseConstraint): |
|
507 |
"""the rql vocabulary constraint : |
|
508 |
||
509 |
limit the proposed values to a set of entities returned by a rql query, |
|
510 |
but this is not enforced at the repository level |
|
1451 | 511 |
|
0 | 512 |
restriction is additional rql restriction that will be added to |
513 |
a predefined query, where the S and O variables respectivly represent |
|
514 |
the subject and the object of the relation |
|
515 |
""" |
|
1451 | 516 |
|
0 | 517 |
def __init__(self, restriction): |
518 |
self.restriction = restriction |
|
519 |
||
2716
2f6edb0e9626
[schema] yams api update
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2691
diff
changeset
|
520 |
def check_consistency(self, subjschema, objschema, rdef): |
2691
ade319674170
add consistency check on constraints
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2632
diff
changeset
|
521 |
if objschema.is_final(): |
ade319674170
add consistency check on constraints
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2632
diff
changeset
|
522 |
raise BadSchemaDefinition("unique constraint doesn't apply to " |
ade319674170
add consistency check on constraints
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2632
diff
changeset
|
523 |
"final entity type") |
ade319674170
add consistency check on constraints
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2632
diff
changeset
|
524 |
|
0 | 525 |
def serialize(self): |
526 |
return self.restriction |
|
1451 | 527 |
|
0 | 528 |
def deserialize(cls, value): |
529 |
return cls(value) |
|
530 |
deserialize = classmethod(deserialize) |
|
1451 | 531 |
|
0 | 532 |
def check(self, entity, rtype, value): |
533 |
"""return true if the value satisfy the constraint, else false""" |
|
534 |
# implemented as a hook in the repository |
|
535 |
return 1 |
|
536 |
||
537 |
def repo_check(self, session, eidfrom, rtype, eidto): |
|
538 |
"""raise ValidationError if the relation doesn't satisfy the constraint |
|
539 |
""" |
|
540 |
pass # this is a vocabulary constraint, not enforce |
|
1451 | 541 |
|
0 | 542 |
def __str__(self): |
543 |
return self.restriction |
|
544 |
||
545 |
def __repr__(self): |
|
546 |
return '<%s : %s>' % (self.__class__.__name__, repr(self.restriction)) |
|
547 |
||
548 |
||
549 |
class RQLConstraint(RQLVocabularyConstraint): |
|
550 |
"""the rql constraint is similar to the RQLVocabularyConstraint but |
|
551 |
are also enforced at the repository level |
|
552 |
""" |
|
553 |
def exec_query(self, session, eidfrom, eidto): |
|
554 |
rql = 'Any S,O WHERE S eid %(s)s, O eid %(o)s, ' + self.restriction |
|
555 |
return session.unsafe_execute(rql, {'s': eidfrom, 'o': eidto}, |
|
556 |
('s', 'o'), build_descr=False) |
|
557 |
def error(self, eid, rtype, msg): |
|
558 |
raise ValidationError(eid, {rtype: msg}) |
|
1451 | 559 |
|
0 | 560 |
def repo_check(self, session, eidfrom, rtype, eidto): |
561 |
"""raise ValidationError if the relation doesn't satisfy the constraint |
|
562 |
""" |
|
563 |
if not self.exec_query(session, eidfrom, eidto): |
|
564 |
# XXX at this point dunno if the validation error `occured` on |
|
565 |
# eidfrom or eidto (from user interface point of view) |
|
566 |
self.error(eidfrom, rtype, 'constraint %s failed' % self) |
|
567 |
||
568 |
||
569 |
class RQLUniqueConstraint(RQLConstraint): |
|
570 |
"""the unique rql constraint check that the result of the query isn't |
|
571 |
greater than one |
|
572 |
""" |
|
573 |
def repo_check(self, session, eidfrom, rtype, eidto): |
|
574 |
"""raise ValidationError if the relation doesn't satisfy the constraint |
|
575 |
""" |
|
576 |
if len(self.exec_query(session, eidfrom, eidto)) > 1: |
|
577 |
# XXX at this point dunno if the validation error `occured` on |
|
578 |
# eidfrom or eidto (from user interface point of view) |
|
579 |
self.error(eidfrom, rtype, 'unique constraint %s failed' % self) |
|
580 |
||
1451 | 581 |
|
0 | 582 |
def split_expression(rqlstring): |
583 |
for expr in rqlstring.split(','): |
|
584 |
for word in expr.split(): |
|
585 |
yield word |
|
1451 | 586 |
|
0 | 587 |
def normalize_expression(rqlstring): |
588 |
"""normalize an rql expression to ease schema synchronization (avoid |
|
589 |
suppressing and reinserting an expression if only a space has been added/removed |
|
590 |
for instance) |
|
591 |
""" |
|
592 |
return u', '.join(' '.join(expr.split()) for expr in rqlstring.split(',')) |
|
593 |
||
594 |
||
595 |
class RQLExpression(object): |
|
596 |
def __init__(self, expression, mainvars, eid): |
|
597 |
self.eid = eid # eid of the entity representing this rql expression |
|
598 |
if not isinstance(mainvars, unicode): |
|
599 |
mainvars = unicode(mainvars) |
|
600 |
self.mainvars = mainvars |
|
601 |
self.expression = normalize_expression(expression) |
|
602 |
try: |
|
603 |
self.rqlst = parse(self.full_rql, print_errors=False).children[0] |
|
604 |
except RQLSyntaxError: |
|
605 |
raise RQLSyntaxError(expression) |
|
606 |
for mainvar in mainvars.split(','): |
|
607 |
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
|
608 |
_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
|
609 |
'expression %s', mainvar, self) |
1451 | 610 |
|
0 | 611 |
def __str__(self): |
612 |
return self.full_rql |
|
613 |
def __repr__(self): |
|
614 |
return '%s(%s)' % (self.__class__.__name__, self.full_rql) |
|
1451 | 615 |
|
0 | 616 |
def __deepcopy__(self, memo): |
617 |
return self.__class__(self.expression, self.mainvars) |
|
618 |
def __getstate__(self): |
|
619 |
return (self.expression, self.mainvars) |
|
620 |
def __setstate__(self, state): |
|
621 |
self.__init__(*state) |
|
1451 | 622 |
|
0 | 623 |
@cached |
624 |
def transform_has_permission(self): |
|
625 |
found = None |
|
626 |
rqlst = self.rqlst |
|
627 |
for var in rqlst.defined_vars.itervalues(): |
|
628 |
for varref in var.references(): |
|
629 |
rel = varref.relation() |
|
630 |
if rel is None: |
|
631 |
continue |
|
632 |
try: |
|
633 |
prefix, action, suffix = rel.r_type.split('_') |
|
634 |
except ValueError: |
|
635 |
continue |
|
636 |
if prefix != 'has' or suffix != 'permission' or \ |
|
637 |
not action in ('add', 'delete', 'update', 'read'): |
|
638 |
continue |
|
639 |
if found is None: |
|
640 |
found = [] |
|
641 |
rqlst.save_state() |
|
642 |
assert rel.children[0].name == 'U' |
|
643 |
objvar = rel.children[1].children[0].variable |
|
644 |
rqlst.remove_node(rel) |
|
645 |
selected = [v.name for v in rqlst.get_selected_variables()] |
|
646 |
if objvar.name not in selected: |
|
647 |
colindex = len(selected) |
|
648 |
rqlst.add_selected(objvar) |
|
649 |
else: |
|
650 |
colindex = selected.index(objvar.name) |
|
651 |
found.append((action, objvar, colindex)) |
|
652 |
# remove U eid %(u)s if U is not used in any other relation |
|
653 |
uvrefs = rqlst.defined_vars['U'].references() |
|
654 |
if len(uvrefs) == 1: |
|
655 |
rqlst.remove_node(uvrefs[0].relation()) |
|
656 |
if found is not None: |
|
657 |
rql = rqlst.as_string() |
|
658 |
if len(rqlst.selection) == 1 and isinstance(rqlst.where, nodes.Relation): |
|
659 |
# only "Any X WHERE X eid %(x)s" remaining, no need to execute the rql |
|
660 |
keyarg = rqlst.selection[0].name.lower() |
|
661 |
else: |
|
662 |
keyarg = None |
|
663 |
rqlst.recover() |
|
664 |
return rql, found, keyarg |
|
665 |
return rqlst.as_string(), None, None |
|
1451 | 666 |
|
0 | 667 |
def _check(self, session, **kwargs): |
668 |
"""return True if the rql expression is matching the given relation |
|
669 |
between fromeid and toeid |
|
670 |
||
671 |
session may actually be a request as well |
|
672 |
""" |
|
673 |
if self.eid is not None: |
|
674 |
key = (self.eid, tuple(sorted(kwargs.iteritems()))) |
|
675 |
try: |
|
676 |
return session.local_perm_cache[key] |
|
677 |
except KeyError: |
|
678 |
pass |
|
679 |
rql, has_perm_defs, keyarg = self.transform_has_permission() |
|
680 |
if keyarg is None: |
|
681 |
# on the server side, use unsafe_execute, but this is not available |
|
682 |
# on the client side (session is actually a request) |
|
683 |
execute = getattr(session, 'unsafe_execute', session.execute) |
|
684 |
# XXX what if 'u' in kwargs |
|
685 |
cachekey = kwargs.keys() |
|
686 |
kwargs['u'] = session.user.eid |
|
687 |
try: |
|
688 |
rset = execute(rql, kwargs, cachekey, build_descr=True) |
|
689 |
except NotImplementedError: |
|
690 |
self.critical('cant check rql expression, unsupported rql %s', rql) |
|
691 |
if self.eid is not None: |
|
692 |
session.local_perm_cache[key] = False |
|
693 |
return False |
|
694 |
except TypeResolverException, ex: |
|
695 |
# some expression may not be resolvable with current kwargs |
|
696 |
# (type conflict) |
|
697 |
self.warning('%s: %s', rql, str(ex)) |
|
698 |
if self.eid is not None: |
|
699 |
session.local_perm_cache[key] = False |
|
700 |
return False |
|
701 |
else: |
|
702 |
rset = session.eid_rset(kwargs[keyarg]) |
|
703 |
# if no special has_*_permission relation in the rql expression, just |
|
704 |
# check the result set contains something |
|
705 |
if has_perm_defs is None: |
|
706 |
if rset: |
|
707 |
if self.eid is not None: |
|
708 |
session.local_perm_cache[key] = True |
|
709 |
return True |
|
710 |
elif rset: |
|
711 |
# check every special has_*_permission relation is satisfied |
|
712 |
get_eschema = session.vreg.schema.eschema |
|
713 |
try: |
|
714 |
for eaction, var, col in has_perm_defs: |
|
715 |
for i in xrange(len(rset)): |
|
716 |
eschema = get_eschema(rset.description[i][col]) |
|
717 |
eschema.check_perm(session, eaction, rset[i][col]) |
|
718 |
if self.eid is not None: |
|
719 |
session.local_perm_cache[key] = True |
|
720 |
return True |
|
721 |
except Unauthorized: |
|
722 |
pass |
|
723 |
if self.eid is not None: |
|
724 |
session.local_perm_cache[key] = False |
|
725 |
return False |
|
1451 | 726 |
|
0 | 727 |
@property |
728 |
def minimal_rql(self): |
|
729 |
return 'Any %s WHERE %s' % (self.mainvars, self.expression) |
|
730 |
||
731 |
||
732 |
class ERQLExpression(RQLExpression): |
|
733 |
def __init__(self, expression, mainvars=None, eid=None): |
|
734 |
RQLExpression.__init__(self, expression, mainvars or 'X', eid) |
|
735 |
# syntax tree used by read security (inserted in queries when necessary |
|
736 |
self.snippet_rqlst = parse(self.minimal_rql, print_errors=False).children[0] |
|
737 |
||
738 |
@property |
|
739 |
def full_rql(self): |
|
740 |
rql = self.minimal_rql |
|
741 |
rqlst = getattr(self, 'rqlst', None) # may be not set yet |
|
742 |
if rqlst is not None: |
|
743 |
defined = rqlst.defined_vars |
|
744 |
else: |
|
745 |
defined = set(split_expression(self.expression)) |
|
746 |
if 'X' in defined: |
|
747 |
rql += ', X eid %(x)s' |
|
748 |
if 'U' in defined: |
|
749 |
rql += ', U eid %(u)s' |
|
750 |
return rql |
|
1451 | 751 |
|
0 | 752 |
def check(self, session, eid=None): |
753 |
if 'X' in self.rqlst.defined_vars: |
|
754 |
if eid is None: |
|
755 |
return False |
|
756 |
return self._check(session, x=eid) |
|
757 |
return self._check(session) |
|
1451 | 758 |
|
2301
a9e9582d5fb6
obsolete implicit context
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2300
diff
changeset
|
759 |
PyFileReader.context['ERQLExpression'] = yobsolete(ERQLExpression) |
1451 | 760 |
|
0 | 761 |
class RRQLExpression(RQLExpression): |
762 |
def __init__(self, expression, mainvars=None, eid=None): |
|
763 |
if mainvars is None: |
|
764 |
defined = set(split_expression(expression)) |
|
765 |
mainvars = [] |
|
766 |
if 'S' in defined: |
|
767 |
mainvars.append('S') |
|
768 |
if 'O' in defined: |
|
769 |
mainvars.append('O') |
|
770 |
if not mainvars: |
|
771 |
raise Exception('unable to guess selection variables') |
|
772 |
mainvars = ','.join(mainvars) |
|
773 |
RQLExpression.__init__(self, expression, mainvars, eid) |
|
774 |
||
775 |
@property |
|
776 |
def full_rql(self): |
|
777 |
rql = self.minimal_rql |
|
778 |
rqlst = getattr(self, 'rqlst', None) # may be not set yet |
|
779 |
if rqlst is not None: |
|
780 |
defined = rqlst.defined_vars |
|
781 |
else: |
|
782 |
defined = set(split_expression(self.expression)) |
|
783 |
if 'S' in defined: |
|
784 |
rql += ', S eid %(s)s' |
|
785 |
if 'O' in defined: |
|
786 |
rql += ', O eid %(o)s' |
|
787 |
if 'U' in defined: |
|
788 |
rql += ', U eid %(u)s' |
|
789 |
return rql |
|
1451 | 790 |
|
0 | 791 |
def check(self, session, fromeid=None, toeid=None): |
792 |
kwargs = {} |
|
793 |
if 'S' in self.rqlst.defined_vars: |
|
794 |
if fromeid is None: |
|
795 |
return False |
|
796 |
kwargs['s'] = fromeid |
|
797 |
if 'O' in self.rqlst.defined_vars: |
|
798 |
if toeid is None: |
|
799 |
return False |
|
800 |
kwargs['o'] = toeid |
|
801 |
return self._check(session, **kwargs) |
|
1451 | 802 |
|
2301
a9e9582d5fb6
obsolete implicit context
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2300
diff
changeset
|
803 |
PyFileReader.context['RRQLExpression'] = yobsolete(RRQLExpression) |
0 | 804 |
|
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
|
805 |
# workflow extensions ######################################################### |
2460
ce1a7ffc6c90
fix a couple NameErrors
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
2459
diff
changeset
|
806 |
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
|
807 |
|
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 |
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
|
809 |
"""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
|
810 |
(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
|
811 |
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
|
812 |
""" |
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 |
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
|
814 |
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
|
815 |
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
|
816 |
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
|
817 |
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
|
818 |
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
|
819 |
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
|
820 |
# 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
|
821 |
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
|
822 |
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
|
823 |
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
|
824 |
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
|
825 |
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
|
826 |
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
|
827 |
|
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
|
828 |
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
|
829 |
__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
|
830 |
abstract = True |
1451 | 831 |
|
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
|
832 |
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
|
833 |
|
0 | 834 |
# schema loading ############################################################## |
835 |
||
836 |
CONSTRAINTS['RQLConstraint'] = RQLConstraint |
|
837 |
CONSTRAINTS['RQLUniqueConstraint'] = RQLUniqueConstraint |
|
838 |
CONSTRAINTS['RQLVocabularyConstraint'] = RQLVocabularyConstraint |
|
839 |
PyFileReader.context.update(CONSTRAINTS) |
|
840 |
||
841 |
||
842 |
class BootstrapSchemaLoader(SchemaLoader): |
|
843 |
"""cubicweb specific schema loader, loading only schema necessary to read |
|
844 |
the persistent schema |
|
845 |
""" |
|
846 |
schemacls = CubicWebSchema |
|
847 |
||
1034
0356bbfb2f26
fix to pass arguments to base class
sylvain.thenault@logilab.fr
parents:
1016
diff
changeset
|
848 |
def load(self, config, path=(), **kwargs): |
0 | 849 |
"""return a Schema instance from the schema definition read |
850 |
from <directory> |
|
851 |
""" |
|
852 |
self.lib_directory = config.schemas_lib_dir() |
|
853 |
return super(BootstrapSchemaLoader, self).load( |
|
1034
0356bbfb2f26
fix to pass arguments to base class
sylvain.thenault@logilab.fr
parents:
1016
diff
changeset
|
854 |
path, config.appid, register_base_types=False, **kwargs) |
1451 | 855 |
|
0 | 856 |
def _load_definition_files(self, cubes=None): |
857 |
# bootstraping, ignore cubes |
|
2142
098aa2075903
include_schema_files is useless
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
858 |
filepath = join(self.lib_directory, 'bootstrap.py') |
098aa2075903
include_schema_files is useless
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
859 |
self.info('loading %s', filepath) |
098aa2075903
include_schema_files is useless
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
860 |
self.handle_file(filepath) |
1451 | 861 |
|
0 | 862 |
def unhandled_file(self, filepath): |
863 |
"""called when a file without handler associated has been found""" |
|
864 |
self.warning('ignoring file %r', filepath) |
|
865 |
||
866 |
||
867 |
class CubicWebSchemaLoader(BootstrapSchemaLoader): |
|
868 |
"""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
|
869 |
instance's schema |
0 | 870 |
""" |
871 |
||
1034
0356bbfb2f26
fix to pass arguments to base class
sylvain.thenault@logilab.fr
parents:
1016
diff
changeset
|
872 |
def load(self, config, **kwargs): |
0 | 873 |
"""return a Schema instance from the schema definition read |
874 |
from <directory> |
|
875 |
""" |
|
876 |
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
|
877 |
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
|
878 |
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
|
879 |
else: |
2598
a66fe74bd9fc
[R schema] dont give an iterator, it's a trap
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2596
diff
changeset
|
880 |
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
|
881 |
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
|
882 |
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
|
883 |
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
|
884 |
# 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
|
885 |
cleanup_sys_modules([self.lib_directory]) |
0 | 886 |
|
887 |
def _load_definition_files(self, cubes): |
|
2142
098aa2075903
include_schema_files is useless
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
888 |
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
|
889 |
join(self.lib_directory, 'base.py'), |
098aa2075903
include_schema_files is useless
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
890 |
join(self.lib_directory, 'workflow.py'), |
098aa2075903
include_schema_files is useless
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
891 |
join(self.lib_directory, 'Bookmark.py')): |
0 | 892 |
self.info('loading %s', filepath) |
893 |
self.handle_file(filepath) |
|
894 |
for cube in cubes: |
|
895 |
for filepath in self.get_schema_files(cube): |
|
896 |
self.info('loading %s', filepath) |
|
897 |
self.handle_file(filepath) |
|
898 |
||
899 |
||
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
|
900 |
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
|
901 |
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
|
902 |
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
|
903 |
|
0 | 904 |
# _() is just there to add messages to the catalog, don't care about actual |
905 |
# translation |
|
906 |
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
|
907 |
NEED_PERM_FORMATS = [_('text/cubicweb-page-template')] |
0 | 908 |
|
2531
531ea4e7013e
[cleanup] nicer imports
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
2526
diff
changeset
|
909 |
@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
|
910 |
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
|
911 |
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
|
912 |
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
|
913 |
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
|
914 |
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
|
915 |
return self.regular_formats |
0 | 916 |
|
917 |
# XXX monkey patch PyFileReader.import_erschema until bw_normalize_etype is |
|
918 |
# necessary |
|
919 |
orig_import_erschema = PyFileReader.import_erschema |
|
920 |
def bw_import_erschema(self, ertype, schemamod=None, instantiate=True): |
|
921 |
return orig_import_erschema(self, bw_normalize_etype(ertype), schemamod, instantiate) |
|
922 |
PyFileReader.import_erschema = bw_import_erschema |
|
1451 | 923 |
|
0 | 924 |
# XXX itou for some Statement methods |
925 |
from rql import stmts |
|
926 |
orig_get_etype = stmts.ScopeNode.get_etype |
|
927 |
def bw_get_etype(self, name): |
|
928 |
return orig_get_etype(self, bw_normalize_etype(name)) |
|
929 |
stmts.ScopeNode.get_etype = bw_get_etype |
|
930 |
||
931 |
orig_add_main_variable_delete = stmts.Delete.add_main_variable |
|
932 |
def bw_add_main_variable_delete(self, etype, vref): |
|
933 |
return orig_add_main_variable_delete(self, bw_normalize_etype(etype), vref) |
|
934 |
stmts.Delete.add_main_variable = bw_add_main_variable_delete |
|
935 |
||
936 |
orig_add_main_variable_insert = stmts.Insert.add_main_variable |
|
937 |
def bw_add_main_variable_insert(self, etype, vref): |
|
938 |
return orig_add_main_variable_insert(self, bw_normalize_etype(etype), vref) |
|
939 |
stmts.Insert.add_main_variable = bw_add_main_variable_insert |
|
940 |
||
941 |
orig_set_statement_type = stmts.Select.set_statement_type |
|
942 |
def bw_set_statement_type(self, etype): |
|
943 |
return orig_set_statement_type(self, bw_normalize_etype(etype)) |
|
944 |
stmts.Select.set_statement_type = bw_set_statement_type |