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