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