author | Adrien Di Mascio <Adrien.DiMascio@logilab.fr> |
Thu, 28 May 2009 09:20:07 +0200 | |
changeset 1977 | 606923dff11b |
parent 1904 | e23536d29231 |
child 2005 | e8032965f37a |
permissions | -rw-r--r-- |
0 | 1 |
"""Base class for entity objects manipulated in clients |
2 |
||
3 |
:organization: Logilab |
|
1977
606923dff11b
big bunch of copyright / docstring update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1904
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:
1904
diff
changeset
|
6 |
:license: GNU Lesser General Public License, v2.1 - http://www.gnu.org/licenses |
0 | 7 |
""" |
8 |
__docformat__ = "restructuredtext en" |
|
9 |
||
1154 | 10 |
from warnings import warn |
11 |
||
0 | 12 |
from logilab.common import interface |
13 |
from logilab.common.compat import all |
|
14 |
from logilab.common.decorators import cached |
|
1008
f54b4309a3f5
bw compat for vocabulary using new form
sylvain.thenault@logilab.fr
parents:
985
diff
changeset
|
15 |
from logilab.common.deprecation import obsolete |
709 | 16 |
from logilab.mtconverter import TransformData, TransformError, html_escape |
631
99f5852f8604
major selector refactoring (mostly to avoid looking for select parameters on the target class), start accept / interface unification)
sylvain.thenault@logilab.fr
parents:
479
diff
changeset
|
17 |
|
0 | 18 |
from rql.utils import rqlvar_maker |
19 |
||
20 |
from cubicweb import Unauthorized |
|
21 |
from cubicweb.rset import ResultSet |
|
692
800592b8d39b
replace deprecated cubicweb.common.selectors by its new module path (cubicweb.selectors)
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
631
diff
changeset
|
22 |
from cubicweb.selectors import yes |
707 | 23 |
from cubicweb.appobject import AppRsetObject |
709 | 24 |
from cubicweb.schema import RQLVocabularyConstraint, RQLConstraint, bw_normalize_etype |
25 |
||
26 |
try: |
|
27 |
from cubicweb.common.uilib import printable_value, soup2xhtml |
|
28 |
from cubicweb.common.mixins import MI_REL_TRIGGERS |
|
29 |
from cubicweb.common.mttransforms import ENGINE |
|
30 |
except ImportError: |
|
31 |
# missing -common |
|
32 |
MI_REL_TRIGGERS = {} |
|
0 | 33 |
|
34 |
_marker = object() |
|
35 |
||
36 |
def greater_card(rschema, subjtypes, objtypes, index): |
|
37 |
for subjtype in subjtypes: |
|
38 |
for objtype in objtypes: |
|
39 |
card = rschema.rproperty(subjtype, objtype, 'cardinality')[index] |
|
40 |
if card in '+*': |
|
41 |
return card |
|
42 |
return '1' |
|
43 |
||
44 |
||
1498
2c6eec0b46b9
fix imports, cleanup, repair some ajax calls
sylvain.thenault@logilab.fr
parents:
1474
diff
changeset
|
45 |
_MODE_TAGS = set(('link', 'create')) |
2c6eec0b46b9
fix imports, cleanup, repair some ajax calls
sylvain.thenault@logilab.fr
parents:
1474
diff
changeset
|
46 |
_CATEGORY_TAGS = set(('primary', 'secondary', 'generic', 'generated')) # , 'metadata')) |
0 | 47 |
|
1154 | 48 |
try: |
1498
2c6eec0b46b9
fix imports, cleanup, repair some ajax calls
sylvain.thenault@logilab.fr
parents:
1474
diff
changeset
|
49 |
from cubicweb.web import formwidgets, uicfg |
0 | 50 |
|
1498
2c6eec0b46b9
fix imports, cleanup, repair some ajax calls
sylvain.thenault@logilab.fr
parents:
1474
diff
changeset
|
51 |
def _dispatch_rtags(tags, rtype, role, stype, otype): |
1154 | 52 |
for tag in tags: |
1498
2c6eec0b46b9
fix imports, cleanup, repair some ajax calls
sylvain.thenault@logilab.fr
parents:
1474
diff
changeset
|
53 |
if tag in _MODE_TAGS: |
1739 | 54 |
uicfg.actionbox_appearsin_addmenu.tag_relation( |
55 |
(stype, rtype, otype, role), tag == 'create') |
|
1498
2c6eec0b46b9
fix imports, cleanup, repair some ajax calls
sylvain.thenault@logilab.fr
parents:
1474
diff
changeset
|
56 |
elif tag in _CATEGORY_TAGS: |
1739 | 57 |
uicfg.autoform_section.tag_relation((stype, rtype, otype, role), |
58 |
tag) |
|
1177
7074698c6522
fix support for old __rtags__ and widgets
sylvain.thenault@logilab.fr
parents:
1154
diff
changeset
|
59 |
elif tag == 'inlineview': |
1739 | 60 |
uicfg.autoform_is_inlined.tag_relation((stype, rtype, otype, role), True) |
1154 | 61 |
else: |
62 |
raise ValueError(tag) |
|
1471
c889c3bcf5ec
new parent_classes method (cached)
sylvain.thenault@logilab.fr
parents:
1435
diff
changeset
|
63 |
|
1154 | 64 |
except ImportError: |
1734
e8673144bc74
access to rwidgets through uicfg, removing buggy import breaking bw compat on the way
sylvain.thenault@logilab.fr
parents:
1721
diff
changeset
|
65 |
|
1498
2c6eec0b46b9
fix imports, cleanup, repair some ajax calls
sylvain.thenault@logilab.fr
parents:
1474
diff
changeset
|
66 |
_dispatch_rtags = None |
1177
7074698c6522
fix support for old __rtags__ and widgets
sylvain.thenault@logilab.fr
parents:
1154
diff
changeset
|
67 |
|
7074698c6522
fix support for old __rtags__ and widgets
sylvain.thenault@logilab.fr
parents:
1154
diff
changeset
|
68 |
def _get_etype(bases, classdict): |
7074698c6522
fix support for old __rtags__ and widgets
sylvain.thenault@logilab.fr
parents:
1154
diff
changeset
|
69 |
try: |
7074698c6522
fix support for old __rtags__ and widgets
sylvain.thenault@logilab.fr
parents:
1154
diff
changeset
|
70 |
return classdict['id'] |
7074698c6522
fix support for old __rtags__ and widgets
sylvain.thenault@logilab.fr
parents:
1154
diff
changeset
|
71 |
except KeyError: |
7074698c6522
fix support for old __rtags__ and widgets
sylvain.thenault@logilab.fr
parents:
1154
diff
changeset
|
72 |
for base in bases: |
7074698c6522
fix support for old __rtags__ and widgets
sylvain.thenault@logilab.fr
parents:
1154
diff
changeset
|
73 |
etype = getattr(base, 'id', None) |
7074698c6522
fix support for old __rtags__ and widgets
sylvain.thenault@logilab.fr
parents:
1154
diff
changeset
|
74 |
if etype and etype != 'Any': |
7074698c6522
fix support for old __rtags__ and widgets
sylvain.thenault@logilab.fr
parents:
1154
diff
changeset
|
75 |
return etype |
1474 | 76 |
|
1177
7074698c6522
fix support for old __rtags__ and widgets
sylvain.thenault@logilab.fr
parents:
1154
diff
changeset
|
77 |
def _get_defs(attr, name, bases, classdict): |
7074698c6522
fix support for old __rtags__ and widgets
sylvain.thenault@logilab.fr
parents:
1154
diff
changeset
|
78 |
try: |
7074698c6522
fix support for old __rtags__ and widgets
sylvain.thenault@logilab.fr
parents:
1154
diff
changeset
|
79 |
yield name, classdict.pop(attr) |
7074698c6522
fix support for old __rtags__ and widgets
sylvain.thenault@logilab.fr
parents:
1154
diff
changeset
|
80 |
except KeyError: |
7074698c6522
fix support for old __rtags__ and widgets
sylvain.thenault@logilab.fr
parents:
1154
diff
changeset
|
81 |
for base in bases: |
7074698c6522
fix support for old __rtags__ and widgets
sylvain.thenault@logilab.fr
parents:
1154
diff
changeset
|
82 |
try: |
7074698c6522
fix support for old __rtags__ and widgets
sylvain.thenault@logilab.fr
parents:
1154
diff
changeset
|
83 |
value = getattr(base, attr) |
7074698c6522
fix support for old __rtags__ and widgets
sylvain.thenault@logilab.fr
parents:
1154
diff
changeset
|
84 |
delattr(base, attr) |
7074698c6522
fix support for old __rtags__ and widgets
sylvain.thenault@logilab.fr
parents:
1154
diff
changeset
|
85 |
yield base.__name__, value |
7074698c6522
fix support for old __rtags__ and widgets
sylvain.thenault@logilab.fr
parents:
1154
diff
changeset
|
86 |
except AttributeError: |
7074698c6522
fix support for old __rtags__ and widgets
sylvain.thenault@logilab.fr
parents:
1154
diff
changeset
|
87 |
continue |
1474 | 88 |
|
1498
2c6eec0b46b9
fix imports, cleanup, repair some ajax calls
sylvain.thenault@logilab.fr
parents:
1474
diff
changeset
|
89 |
class _metaentity(type): |
0 | 90 |
"""this metaclass sets the relation tags on the entity class |
91 |
and deals with the `widgets` attribute |
|
92 |
""" |
|
93 |
def __new__(mcs, name, bases, classdict): |
|
94 |
# collect baseclass' rtags |
|
1177
7074698c6522
fix support for old __rtags__ and widgets
sylvain.thenault@logilab.fr
parents:
1154
diff
changeset
|
95 |
etype = _get_etype(bases, classdict) |
1498
2c6eec0b46b9
fix imports, cleanup, repair some ajax calls
sylvain.thenault@logilab.fr
parents:
1474
diff
changeset
|
96 |
if etype and _dispatch_rtags is not None: |
1177
7074698c6522
fix support for old __rtags__ and widgets
sylvain.thenault@logilab.fr
parents:
1154
diff
changeset
|
97 |
for name, rtags in _get_defs('__rtags__', name, bases, classdict): |
7074698c6522
fix support for old __rtags__ and widgets
sylvain.thenault@logilab.fr
parents:
1154
diff
changeset
|
98 |
warn('%s: __rtags__ is deprecated' % name, DeprecationWarning) |
7074698c6522
fix support for old __rtags__ and widgets
sylvain.thenault@logilab.fr
parents:
1154
diff
changeset
|
99 |
for relation, tags in rtags.iteritems(): |
7074698c6522
fix support for old __rtags__ and widgets
sylvain.thenault@logilab.fr
parents:
1154
diff
changeset
|
100 |
# tags must become an iterable |
7074698c6522
fix support for old __rtags__ and widgets
sylvain.thenault@logilab.fr
parents:
1154
diff
changeset
|
101 |
if isinstance(tags, basestring): |
7074698c6522
fix support for old __rtags__ and widgets
sylvain.thenault@logilab.fr
parents:
1154
diff
changeset
|
102 |
tags = (tags,) |
7074698c6522
fix support for old __rtags__ and widgets
sylvain.thenault@logilab.fr
parents:
1154
diff
changeset
|
103 |
# relation must become a 3-uple (rtype, targettype, role) |
7074698c6522
fix support for old __rtags__ and widgets
sylvain.thenault@logilab.fr
parents:
1154
diff
changeset
|
104 |
if isinstance(relation, basestring): |
1498
2c6eec0b46b9
fix imports, cleanup, repair some ajax calls
sylvain.thenault@logilab.fr
parents:
1474
diff
changeset
|
105 |
_dispatch_rtags(tags, relation, 'subject', etype, '*') |
2c6eec0b46b9
fix imports, cleanup, repair some ajax calls
sylvain.thenault@logilab.fr
parents:
1474
diff
changeset
|
106 |
_dispatch_rtags(tags, relation, 'object', '*', etype) |
1177
7074698c6522
fix support for old __rtags__ and widgets
sylvain.thenault@logilab.fr
parents:
1154
diff
changeset
|
107 |
elif len(relation) == 1: # useful ? |
1498
2c6eec0b46b9
fix imports, cleanup, repair some ajax calls
sylvain.thenault@logilab.fr
parents:
1474
diff
changeset
|
108 |
_dispatch_rtags(tags, relation[0], 'subject', etype, '*') |
2c6eec0b46b9
fix imports, cleanup, repair some ajax calls
sylvain.thenault@logilab.fr
parents:
1474
diff
changeset
|
109 |
_dispatch_rtags(tags, relation[0], 'object', '*', etype) |
1177
7074698c6522
fix support for old __rtags__ and widgets
sylvain.thenault@logilab.fr
parents:
1154
diff
changeset
|
110 |
elif len(relation) == 2: |
7074698c6522
fix support for old __rtags__ and widgets
sylvain.thenault@logilab.fr
parents:
1154
diff
changeset
|
111 |
rtype, ttype = relation |
7074698c6522
fix support for old __rtags__ and widgets
sylvain.thenault@logilab.fr
parents:
1154
diff
changeset
|
112 |
ttype = bw_normalize_etype(ttype) # XXX bw compat |
1498
2c6eec0b46b9
fix imports, cleanup, repair some ajax calls
sylvain.thenault@logilab.fr
parents:
1474
diff
changeset
|
113 |
_dispatch_rtags(tags, rtype, 'subject', etype, ttype) |
2c6eec0b46b9
fix imports, cleanup, repair some ajax calls
sylvain.thenault@logilab.fr
parents:
1474
diff
changeset
|
114 |
_dispatch_rtags(tags, rtype, 'object', ttype, etype) |
1177
7074698c6522
fix support for old __rtags__ and widgets
sylvain.thenault@logilab.fr
parents:
1154
diff
changeset
|
115 |
elif len(relation) == 3: |
7074698c6522
fix support for old __rtags__ and widgets
sylvain.thenault@logilab.fr
parents:
1154
diff
changeset
|
116 |
rtype, ttype, role = relation |
7074698c6522
fix support for old __rtags__ and widgets
sylvain.thenault@logilab.fr
parents:
1154
diff
changeset
|
117 |
ttype = bw_normalize_etype(ttype) |
7074698c6522
fix support for old __rtags__ and widgets
sylvain.thenault@logilab.fr
parents:
1154
diff
changeset
|
118 |
if role == 'subject': |
1498
2c6eec0b46b9
fix imports, cleanup, repair some ajax calls
sylvain.thenault@logilab.fr
parents:
1474
diff
changeset
|
119 |
_dispatch_rtags(tags, rtype, 'subject', etype, ttype) |
1177
7074698c6522
fix support for old __rtags__ and widgets
sylvain.thenault@logilab.fr
parents:
1154
diff
changeset
|
120 |
else: |
1498
2c6eec0b46b9
fix imports, cleanup, repair some ajax calls
sylvain.thenault@logilab.fr
parents:
1474
diff
changeset
|
121 |
_dispatch_rtags(tags, rtype, 'object', ttype, etype) |
1154 | 122 |
else: |
1177
7074698c6522
fix support for old __rtags__ and widgets
sylvain.thenault@logilab.fr
parents:
1154
diff
changeset
|
123 |
raise ValueError('bad rtag definition (%r)' % (relation,)) |
7074698c6522
fix support for old __rtags__ and widgets
sylvain.thenault@logilab.fr
parents:
1154
diff
changeset
|
124 |
for name, widgets in _get_defs('widgets', name, bases, classdict): |
7074698c6522
fix support for old __rtags__ and widgets
sylvain.thenault@logilab.fr
parents:
1154
diff
changeset
|
125 |
warn('%s: widgets is deprecated' % name, DeprecationWarning) |
7074698c6522
fix support for old __rtags__ and widgets
sylvain.thenault@logilab.fr
parents:
1154
diff
changeset
|
126 |
for rtype, wdgname in widgets.iteritems(): |
1804 | 127 |
if wdgname in ('URLWidget', 'EmbededURLWidget', 'RawDynamicComboBoxWidget'): |
1269 | 128 |
warn('%s widget is deprecated' % wdgname, DeprecationWarning) |
129 |
continue |
|
1313
9cff1eee0208
put class, not class name into rwidgets. New rfields rtags to specify a field for a relation
sylvain.thenault@logilab.fr
parents:
1269
diff
changeset
|
130 |
if wdgname == 'StringWidget': |
9cff1eee0208
put class, not class name into rwidgets. New rfields rtags to specify a field for a relation
sylvain.thenault@logilab.fr
parents:
1269
diff
changeset
|
131 |
wdgname = 'TextInput' |
9cff1eee0208
put class, not class name into rwidgets. New rfields rtags to specify a field for a relation
sylvain.thenault@logilab.fr
parents:
1269
diff
changeset
|
132 |
widget = getattr(formwidgets, wdgname) |
1582 | 133 |
assert hasattr(widget, 'render') |
1754
c9c7618a90de
autoform_widget superseeded by autoform_field_kwargs (api change addiction :-/)
sylvain.thenault@logilab.fr
parents:
1739
diff
changeset
|
134 |
uicfg.autoform_field_kwargs.tag_subject_of( |
c9c7618a90de
autoform_widget superseeded by autoform_field_kwargs (api change addiction :-/)
sylvain.thenault@logilab.fr
parents:
1739
diff
changeset
|
135 |
(etype, rtype, '*'), {'widget': widget}) |
1498
2c6eec0b46b9
fix imports, cleanup, repair some ajax calls
sylvain.thenault@logilab.fr
parents:
1474
diff
changeset
|
136 |
return super(_metaentity, mcs).__new__(mcs, name, bases, classdict) |
0 | 137 |
|
138 |
||
139 |
class Entity(AppRsetObject, dict): |
|
140 |
"""an entity instance has e_schema automagically set on |
|
141 |
the class and instances has access to their issuing cursor. |
|
1474 | 142 |
|
0 | 143 |
A property is set for each attribute and relation on each entity's type |
144 |
class. Becare that among attributes, 'eid' is *NEITHER* stored in the |
|
145 |
dict containment (which acts as a cache for other attributes dynamically |
|
146 |
fetched) |
|
147 |
||
148 |
:type e_schema: `cubicweb.schema.EntitySchema` |
|
149 |
:ivar e_schema: the entity's schema |
|
150 |
||
151 |
:type rest_var: str |
|
152 |
:cvar rest_var: indicates which attribute should be used to build REST urls |
|
153 |
If None is specified, the first non-meta attribute will |
|
154 |
be used |
|
1474 | 155 |
|
0 | 156 |
:type skip_copy_for: list |
157 |
:cvar skip_copy_for: a list of relations that should be skipped when copying |
|
158 |
this kind of entity. Note that some relations such |
|
159 |
as composite relations or relations that have '?1' as object |
|
160 |
cardinality |
|
161 |
""" |
|
1498
2c6eec0b46b9
fix imports, cleanup, repair some ajax calls
sylvain.thenault@logilab.fr
parents:
1474
diff
changeset
|
162 |
__metaclass__ = _metaentity |
0 | 163 |
__registry__ = 'etypes' |
717 | 164 |
__select__ = yes() |
1264
fe2934a7df7f
cleanup, avoid spurious warning
sylvain.thenault@logilab.fr
parents:
1177
diff
changeset
|
165 |
|
1474 | 166 |
# class attributes that must be set in class definition |
0 | 167 |
id = None |
168 |
rest_attr = None |
|
1138
22f634977c95
make pylint happy, fix some bugs on the way
sylvain.thenault@logilab.fr
parents:
1132
diff
changeset
|
169 |
fetch_attrs = None |
0 | 170 |
skip_copy_for = () |
1264
fe2934a7df7f
cleanup, avoid spurious warning
sylvain.thenault@logilab.fr
parents:
1177
diff
changeset
|
171 |
# class attributes set automatically at registration time |
fe2934a7df7f
cleanup, avoid spurious warning
sylvain.thenault@logilab.fr
parents:
1177
diff
changeset
|
172 |
e_schema = None |
1474 | 173 |
|
0 | 174 |
@classmethod |
175 |
def registered(cls, registry): |
|
176 |
"""build class using descriptor at registration time""" |
|
177 |
assert cls.id is not None |
|
178 |
super(Entity, cls).registered(registry) |
|
179 |
if cls.id != 'Any': |
|
180 |
cls.__initialize__() |
|
181 |
return cls |
|
1474 | 182 |
|
0 | 183 |
MODE_TAGS = set(('link', 'create')) |
184 |
CATEGORY_TAGS = set(('primary', 'secondary', 'generic', 'generated')) # , 'metadata')) |
|
185 |
@classmethod |
|
186 |
def __initialize__(cls): |
|
187 |
"""initialize a specific entity class by adding descriptors to access |
|
188 |
entity type's attributes and relations |
|
189 |
""" |
|
190 |
etype = cls.id |
|
191 |
assert etype != 'Any', etype |
|
192 |
cls.e_schema = eschema = cls.schema.eschema(etype) |
|
193 |
for rschema, _ in eschema.attribute_definitions(): |
|
194 |
if rschema.type == 'eid': |
|
195 |
continue |
|
196 |
setattr(cls, rschema.type, Attribute(rschema.type)) |
|
197 |
mixins = [] |
|
198 |
for rschema, _, x in eschema.relation_definitions(): |
|
199 |
if (rschema, x) in MI_REL_TRIGGERS: |
|
200 |
mixin = MI_REL_TRIGGERS[(rschema, x)] |
|
201 |
if not (issubclass(cls, mixin) or mixin in mixins): # already mixed ? |
|
202 |
mixins.append(mixin) |
|
203 |
for iface in getattr(mixin, '__implements__', ()): |
|
204 |
if not interface.implements(cls, iface): |
|
205 |
interface.extend(cls, iface) |
|
206 |
if x == 'subject': |
|
207 |
setattr(cls, rschema.type, SubjectRelation(rschema)) |
|
208 |
else: |
|
209 |
attr = 'reverse_%s' % rschema.type |
|
210 |
setattr(cls, attr, ObjectRelation(rschema)) |
|
211 |
if mixins: |
|
212 |
cls.__bases__ = tuple(mixins + [p for p in cls.__bases__ if not p is object]) |
|
213 |
cls.debug('plugged %s mixins on %s', mixins, etype) |
|
1474 | 214 |
|
0 | 215 |
@classmethod |
216 |
def fetch_rql(cls, user, restriction=None, fetchattrs=None, mainvar='X', |
|
217 |
settype=True, ordermethod='fetch_order'): |
|
218 |
"""return a rql to fetch all entities of the class type""" |
|
219 |
restrictions = restriction or [] |
|
220 |
if settype: |
|
221 |
restrictions.append('%s is %s' % (mainvar, cls.id)) |
|
222 |
if fetchattrs is None: |
|
223 |
fetchattrs = cls.fetch_attrs |
|
224 |
selection = [mainvar] |
|
225 |
orderby = [] |
|
226 |
# start from 26 to avoid possible conflicts with X |
|
227 |
varmaker = rqlvar_maker(index=26) |
|
228 |
cls._fetch_restrictions(mainvar, varmaker, fetchattrs, selection, |
|
229 |
orderby, restrictions, user, ordermethod) |
|
230 |
rql = 'Any %s' % ','.join(selection) |
|
231 |
if orderby: |
|
232 |
rql += ' ORDERBY %s' % ','.join(orderby) |
|
233 |
rql += ' WHERE %s' % ', '.join(restrictions) |
|
234 |
return rql |
|
1474 | 235 |
|
0 | 236 |
@classmethod |
237 |
def _fetch_restrictions(cls, mainvar, varmaker, fetchattrs, |
|
238 |
selection, orderby, restrictions, user, |
|
239 |
ordermethod='fetch_order', visited=None): |
|
240 |
eschema = cls.e_schema |
|
241 |
if visited is None: |
|
242 |
visited = set((eschema.type,)) |
|
243 |
elif eschema.type in visited: |
|
244 |
# avoid infinite recursion |
|
245 |
return |
|
246 |
else: |
|
247 |
visited.add(eschema.type) |
|
248 |
_fetchattrs = [] |
|
249 |
for attr in fetchattrs: |
|
250 |
try: |
|
251 |
rschema = eschema.subject_relation(attr) |
|
252 |
except KeyError: |
|
253 |
cls.warning('skipping fetch_attr %s defined in %s (not found in schema)', |
|
254 |
attr, cls.id) |
|
255 |
continue |
|
256 |
if not user.matching_groups(rschema.get_groups('read')): |
|
257 |
continue |
|
258 |
var = varmaker.next() |
|
259 |
selection.append(var) |
|
260 |
restriction = '%s %s %s' % (mainvar, attr, var) |
|
261 |
restrictions.append(restriction) |
|
262 |
if not rschema.is_final(): |
|
263 |
# XXX this does not handle several destination types |
|
264 |
desttype = rschema.objects(eschema.type)[0] |
|
265 |
card = rschema.rproperty(eschema, desttype, 'cardinality')[0] |
|
266 |
if card not in '?1': |
|
267 |
selection.pop() |
|
268 |
restrictions.pop() |
|
269 |
continue |
|
270 |
if card == '?': |
|
271 |
restrictions[-1] += '?' # left outer join if not mandatory |
|
272 |
destcls = cls.vreg.etype_class(desttype) |
|
273 |
destcls._fetch_restrictions(var, varmaker, destcls.fetch_attrs, |
|
274 |
selection, orderby, restrictions, |
|
275 |
user, ordermethod, visited=visited) |
|
276 |
orderterm = getattr(cls, ordermethod)(attr, var) |
|
277 |
if orderterm: |
|
278 |
orderby.append(orderterm) |
|
279 |
return selection, orderby, restrictions |
|
280 |
||
1471
c889c3bcf5ec
new parent_classes method (cached)
sylvain.thenault@logilab.fr
parents:
1435
diff
changeset
|
281 |
@classmethod |
c889c3bcf5ec
new parent_classes method (cached)
sylvain.thenault@logilab.fr
parents:
1435
diff
changeset
|
282 |
@cached |
c889c3bcf5ec
new parent_classes method (cached)
sylvain.thenault@logilab.fr
parents:
1435
diff
changeset
|
283 |
def parent_classes(cls): |
c889c3bcf5ec
new parent_classes method (cached)
sylvain.thenault@logilab.fr
parents:
1435
diff
changeset
|
284 |
parents = [cls.vreg.etype_class(e.type) for e in cls.e_schema.ancestors()] |
c889c3bcf5ec
new parent_classes method (cached)
sylvain.thenault@logilab.fr
parents:
1435
diff
changeset
|
285 |
parents.append(cls.vreg.etype_class('Any')) |
c889c3bcf5ec
new parent_classes method (cached)
sylvain.thenault@logilab.fr
parents:
1435
diff
changeset
|
286 |
return parents |
c889c3bcf5ec
new parent_classes method (cached)
sylvain.thenault@logilab.fr
parents:
1435
diff
changeset
|
287 |
|
1840
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
288 |
@classmethod |
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
289 |
@cached |
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
290 |
def _rest_attr_info(cls): |
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
291 |
mainattr, needcheck = 'eid', True |
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
292 |
if cls.rest_attr: |
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
293 |
mainattr = cls.rest_attr |
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
294 |
needcheck = not cls.e_schema.has_unique_values(mainattr) |
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
295 |
else: |
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
296 |
for rschema in cls.e_schema.subject_relations(): |
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
297 |
if rschema.is_final() and rschema != 'eid' and cls.e_schema.has_unique_values(rschema): |
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
298 |
mainattr = str(rschema) |
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
299 |
needcheck = False |
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
300 |
break |
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
301 |
if mainattr == 'eid': |
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
302 |
needcheck = False |
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
303 |
return mainattr, needcheck |
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
304 |
|
1435
6cd6172718bb
allow to instantiate an entity without rset
sylvain.thenault@logilab.fr
parents:
1363
diff
changeset
|
305 |
def __init__(self, req, rset=None, row=None, col=0): |
1363
d8f2c3953eb5
AppRsetObject now handle row and col
sylvain.thenault@logilab.fr
parents:
1360
diff
changeset
|
306 |
AppRsetObject.__init__(self, req, rset, row, col) |
0 | 307 |
dict.__init__(self) |
308 |
self._related_cache = {} |
|
309 |
if rset is not None: |
|
310 |
self.eid = rset[row][col] |
|
311 |
else: |
|
312 |
self.eid = None |
|
313 |
self._is_saved = True |
|
1474 | 314 |
|
0 | 315 |
def __repr__(self): |
316 |
return '<Entity %s %s %s at %s>' % ( |
|
317 |
self.e_schema, self.eid, self.keys(), id(self)) |
|
318 |
||
319 |
def __nonzero__(self): |
|
320 |
return True |
|
321 |
||
322 |
def __hash__(self): |
|
323 |
return id(self) |
|
324 |
||
325 |
def pre_add_hook(self): |
|
326 |
"""hook called by the repository before doing anything to add the entity |
|
327 |
(before_add entity hooks have not been called yet). This give the |
|
328 |
occasion to do weird stuff such as autocast (File -> Image for instance). |
|
1474 | 329 |
|
0 | 330 |
This method must return the actual entity to be added. |
331 |
""" |
|
332 |
return self |
|
1474 | 333 |
|
0 | 334 |
def set_eid(self, eid): |
335 |
self.eid = self['eid'] = eid |
|
336 |
||
337 |
def has_eid(self): |
|
338 |
"""return True if the entity has an attributed eid (False |
|
339 |
meaning that the entity has to be created |
|
340 |
""" |
|
341 |
try: |
|
342 |
int(self.eid) |
|
343 |
return True |
|
344 |
except (ValueError, TypeError): |
|
345 |
return False |
|
346 |
||
347 |
def is_saved(self): |
|
348 |
"""during entity creation, there is some time during which the entity |
|
349 |
has an eid attributed though it's not saved (eg during before_add_entity |
|
350 |
hooks). You can use this method to ensure the entity has an eid *and* is |
|
351 |
saved in its source. |
|
352 |
""" |
|
353 |
return self.has_eid() and self._is_saved |
|
1474 | 354 |
|
0 | 355 |
@cached |
356 |
def metainformation(self): |
|
357 |
res = dict(zip(('type', 'source', 'extid'), self.req.describe(self.eid))) |
|
358 |
res['source'] = self.req.source_defs()[res['source']] |
|
359 |
return res |
|
360 |
||
475
b32a5772ff06
should clear local perm cache if first attempt failed
sylvain.thenault@logilab.fr
parents:
413
diff
changeset
|
361 |
def clear_local_perm_cache(self, action): |
b32a5772ff06
should clear local perm cache if first attempt failed
sylvain.thenault@logilab.fr
parents:
413
diff
changeset
|
362 |
for rqlexpr in self.e_schema.get_rqlexprs(action): |
b32a5772ff06
should clear local perm cache if first attempt failed
sylvain.thenault@logilab.fr
parents:
413
diff
changeset
|
363 |
self.req.local_perm_cache.pop((rqlexpr.eid, (('x', self.eid),)), None) |
b32a5772ff06
should clear local perm cache if first attempt failed
sylvain.thenault@logilab.fr
parents:
413
diff
changeset
|
364 |
|
0 | 365 |
def check_perm(self, action): |
366 |
self.e_schema.check_perm(self.req, action, self.eid) |
|
367 |
||
368 |
def has_perm(self, action): |
|
369 |
return self.e_schema.has_perm(self.req, action, self.eid) |
|
1474 | 370 |
|
0 | 371 |
def view(self, vid, __registry='views', **kwargs): |
372 |
"""shortcut to apply a view on this entity""" |
|
373 |
return self.vreg.render(__registry, vid, self.req, rset=self.rset, |
|
374 |
row=self.row, col=self.col, **kwargs) |
|
375 |
||
376 |
def absolute_url(self, method=None, **kwargs): |
|
377 |
"""return an absolute url to view this entity""" |
|
378 |
# in linksearch mode, we don't want external urls else selecting |
|
379 |
# the object for use in the relation is tricky |
|
380 |
# XXX search_state is web specific |
|
381 |
if getattr(self.req, 'search_state', ('normal',))[0] == 'normal': |
|
382 |
kwargs['base_url'] = self.metainformation()['source'].get('base-url') |
|
1904
e23536d29231
minor refactoring of absolute_url()
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
1842
diff
changeset
|
383 |
if method in (None, 'view'): |
1842
c7a22540d6f7
add some bw compat code for old rest_path prototype
sylvain.thenault@logilab.fr
parents:
1840
diff
changeset
|
384 |
try: |
c7a22540d6f7
add some bw compat code for old rest_path prototype
sylvain.thenault@logilab.fr
parents:
1840
diff
changeset
|
385 |
kwargs['_restpath'] = self.rest_path(kwargs.get('base_url')) |
c7a22540d6f7
add some bw compat code for old rest_path prototype
sylvain.thenault@logilab.fr
parents:
1840
diff
changeset
|
386 |
except TypeError: |
c7a22540d6f7
add some bw compat code for old rest_path prototype
sylvain.thenault@logilab.fr
parents:
1840
diff
changeset
|
387 |
warn('%s: rest_path() now take use_ext_eid argument, ' |
c7a22540d6f7
add some bw compat code for old rest_path prototype
sylvain.thenault@logilab.fr
parents:
1840
diff
changeset
|
388 |
'please update' % self.id, DeprecationWarning) |
c7a22540d6f7
add some bw compat code for old rest_path prototype
sylvain.thenault@logilab.fr
parents:
1840
diff
changeset
|
389 |
kwargs['_restpath'] = self.rest_path() |
0 | 390 |
else: |
391 |
kwargs['rql'] = 'Any X WHERE X eid %s' % self.eid |
|
392 |
return self.build_url(method, **kwargs) |
|
393 |
||
1840
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
394 |
def rest_path(self, use_ext_eid=False): |
0 | 395 |
"""returns a REST-like (relative) path for this entity""" |
396 |
mainattr, needcheck = self._rest_attr_info() |
|
397 |
etype = str(self.e_schema) |
|
1840
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
398 |
path = etype.lower() |
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
399 |
if mainattr != 'eid': |
0 | 400 |
value = getattr(self, mainattr) |
401 |
if value is None: |
|
1840
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
402 |
mainattr = 'eid' |
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
403 |
path += '/eid' |
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
404 |
elif needcheck: |
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
405 |
# make sure url is not ambiguous |
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
406 |
rql = 'Any COUNT(X) WHERE X is %s, X %s %%(value)s' % ( |
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
407 |
etype, mainattr) |
1904
e23536d29231
minor refactoring of absolute_url()
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
1842
diff
changeset
|
408 |
nbresults = self.req.execute(rql, {'value' : value})[0][0] |
e23536d29231
minor refactoring of absolute_url()
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
1842
diff
changeset
|
409 |
if nbresults != 1: # ambiguity? |
e23536d29231
minor refactoring of absolute_url()
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
1842
diff
changeset
|
410 |
mainattr = 'eid' |
e23536d29231
minor refactoring of absolute_url()
Nicolas Chauvat <nicolas.chauvat@logilab.fr>
parents:
1842
diff
changeset
|
411 |
path += '/eid' |
0 | 412 |
if mainattr == 'eid': |
1840
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
413 |
if use_ext_eid: |
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
414 |
value = self.metainformation()['extid'] |
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
415 |
else: |
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
416 |
value = self.eid |
f4b5c15d1147
test and fix #342997: local eid used for absolute_url of external entities
sylvain.thenault@logilab.fr
parents:
1804
diff
changeset
|
417 |
return '%s/%s' % (path, self.req.url_quote(value)) |
0 | 418 |
|
1360
13ae1121835e
rename attribute_metadata method to attr_metadata to save a few chars
sylvain.thenault@logilab.fr
parents:
1313
diff
changeset
|
419 |
def attr_metadata(self, attr, metadata): |
1101
0c067de38e46
unification of meta-attributes handling:
sylvain.thenault@logilab.fr
parents:
1098
diff
changeset
|
420 |
"""return a metadata for an attribute (None if unspecified)""" |
0c067de38e46
unification of meta-attributes handling:
sylvain.thenault@logilab.fr
parents:
1098
diff
changeset
|
421 |
value = getattr(self, '%s_%s' % (attr, metadata), None) |
0c067de38e46
unification of meta-attributes handling:
sylvain.thenault@logilab.fr
parents:
1098
diff
changeset
|
422 |
if value is None and metadata == 'encoding': |
0c067de38e46
unification of meta-attributes handling:
sylvain.thenault@logilab.fr
parents:
1098
diff
changeset
|
423 |
value = self.vreg.property_value('ui.encoding') |
0c067de38e46
unification of meta-attributes handling:
sylvain.thenault@logilab.fr
parents:
1098
diff
changeset
|
424 |
return value |
0 | 425 |
|
426 |
def printable_value(self, attr, value=_marker, attrtype=None, |
|
427 |
format='text/html', displaytime=True): |
|
428 |
"""return a displayable value (i.e. unicode string) which may contains |
|
429 |
html tags |
|
430 |
""" |
|
431 |
attr = str(attr) |
|
432 |
if value is _marker: |
|
433 |
value = getattr(self, attr) |
|
434 |
if isinstance(value, basestring): |
|
435 |
value = value.strip() |
|
436 |
if value is None or value == '': # don't use "not", 0 is an acceptable value |
|
437 |
return u'' |
|
438 |
if attrtype is None: |
|
439 |
attrtype = self.e_schema.destination(attr) |
|
440 |
props = self.e_schema.rproperties(attr) |
|
441 |
if attrtype == 'String': |
|
442 |
# internalinalized *and* formatted string such as schema |
|
443 |
# description... |
|
444 |
if props.get('internationalizable'): |
|
445 |
value = self.req._(value) |
|
1360
13ae1121835e
rename attribute_metadata method to attr_metadata to save a few chars
sylvain.thenault@logilab.fr
parents:
1313
diff
changeset
|
446 |
attrformat = self.attr_metadata(attr, 'format') |
0 | 447 |
if attrformat: |
448 |
return self.mtc_transform(value, attrformat, format, |
|
449 |
self.req.encoding) |
|
450 |
elif attrtype == 'Bytes': |
|
1360
13ae1121835e
rename attribute_metadata method to attr_metadata to save a few chars
sylvain.thenault@logilab.fr
parents:
1313
diff
changeset
|
451 |
attrformat = self.attr_metadata(attr, 'format') |
0 | 452 |
if attrformat: |
1360
13ae1121835e
rename attribute_metadata method to attr_metadata to save a few chars
sylvain.thenault@logilab.fr
parents:
1313
diff
changeset
|
453 |
encoding = self.attr_metadata(attr, 'encoding') |
0 | 454 |
return self.mtc_transform(value.getvalue(), attrformat, format, |
455 |
encoding) |
|
456 |
return u'' |
|
457 |
value = printable_value(self.req, attrtype, value, props, displaytime) |
|
458 |
if format == 'text/html': |
|
459 |
value = html_escape(value) |
|
460 |
return value |
|
461 |
||
462 |
def mtc_transform(self, data, format, target_format, encoding, |
|
463 |
_engine=ENGINE): |
|
464 |
trdata = TransformData(data, format, encoding, appobject=self) |
|
465 |
data = _engine.convert(trdata, target_format).decode() |
|
466 |
if format == 'text/html': |
|
1474 | 467 |
data = soup2xhtml(data, self.req.encoding) |
0 | 468 |
return data |
1474 | 469 |
|
0 | 470 |
# entity cloning ########################################################## |
471 |
||
472 |
def copy_relations(self, ceid): |
|
473 |
"""copy relations of the object with the given eid on this object |
|
474 |
||
475 |
By default meta and composite relations are skipped. |
|
476 |
Overrides this if you want another behaviour |
|
477 |
""" |
|
478 |
assert self.has_eid() |
|
479 |
execute = self.req.execute |
|
480 |
for rschema in self.e_schema.subject_relations(): |
|
481 |
if rschema.meta or rschema.is_final(): |
|
482 |
continue |
|
483 |
# skip already defined relations |
|
484 |
if getattr(self, rschema.type): |
|
485 |
continue |
|
486 |
if rschema.type in self.skip_copy_for: |
|
487 |
continue |
|
488 |
if rschema.type == 'in_state': |
|
489 |
# if the workflow is defining an initial state (XXX AND we are |
|
490 |
# not in the managers group? not done to be more consistent) |
|
491 |
# don't try to copy in_state |
|
492 |
if execute('Any S WHERE S state_of ET, ET initial_state S,' |
|
493 |
'ET name %(etype)s', {'etype': str(self.e_schema)}): |
|
494 |
continue |
|
495 |
# skip composite relation |
|
496 |
if self.e_schema.subjrproperty(rschema, 'composite'): |
|
497 |
continue |
|
498 |
# skip relation with card in ?1 else we either change the copied |
|
499 |
# object (inlined relation) or inserting some inconsistency |
|
500 |
if self.e_schema.subjrproperty(rschema, 'cardinality')[1] in '?1': |
|
501 |
continue |
|
502 |
rql = 'SET X %s V WHERE X eid %%(x)s, Y eid %%(y)s, Y %s V' % ( |
|
503 |
rschema.type, rschema.type) |
|
504 |
execute(rql, {'x': self.eid, 'y': ceid}, ('x', 'y')) |
|
505 |
self.clear_related_cache(rschema.type, 'subject') |
|
506 |
for rschema in self.e_schema.object_relations(): |
|
507 |
if rschema.meta: |
|
508 |
continue |
|
509 |
# skip already defined relations |
|
510 |
if getattr(self, 'reverse_%s' % rschema.type): |
|
511 |
continue |
|
512 |
# skip composite relation |
|
513 |
if self.e_schema.objrproperty(rschema, 'composite'): |
|
514 |
continue |
|
515 |
# skip relation with card in ?1 else we either change the copied |
|
516 |
# object (inlined relation) or inserting some inconsistency |
|
517 |
if self.e_schema.objrproperty(rschema, 'cardinality')[0] in '?1': |
|
518 |
continue |
|
519 |
rql = 'SET V %s X WHERE X eid %%(x)s, Y eid %%(y)s, V %s Y' % ( |
|
520 |
rschema.type, rschema.type) |
|
521 |
execute(rql, {'x': self.eid, 'y': ceid}, ('x', 'y')) |
|
522 |
self.clear_related_cache(rschema.type, 'object') |
|
523 |
||
524 |
# data fetching methods ################################################### |
|
525 |
||
526 |
@cached |
|
527 |
def as_rset(self): |
|
528 |
"""returns a resultset containing `self` information""" |
|
529 |
rset = ResultSet([(self.eid,)], 'Any X WHERE X eid %(x)s', |
|
530 |
{'x': self.eid}, [(self.id,)]) |
|
531 |
return self.req.decorate_rset(rset) |
|
1474 | 532 |
|
0 | 533 |
def to_complete_relations(self): |
534 |
"""by default complete final relations to when calling .complete()""" |
|
535 |
for rschema in self.e_schema.subject_relations(): |
|
536 |
if rschema.is_final(): |
|
537 |
continue |
|
538 |
if len(rschema.objects(self.e_schema)) > 1: |
|
539 |
# ambigous relations, the querier doesn't handle |
|
540 |
# outer join correctly in this case |
|
541 |
continue |
|
542 |
if rschema.inlined: |
|
543 |
matching_groups = self.req.user.matching_groups |
|
544 |
if matching_groups(rschema.get_groups('read')) and \ |
|
545 |
all(matching_groups(es.get_groups('read')) |
|
546 |
for es in rschema.objects(self.e_schema)): |
|
547 |
yield rschema, 'subject' |
|
1474 | 548 |
|
0 | 549 |
def to_complete_attributes(self, skip_bytes=True): |
550 |
for rschema, attrschema in self.e_schema.attribute_definitions(): |
|
551 |
# skip binary data by default |
|
552 |
if skip_bytes and attrschema.type == 'Bytes': |
|
553 |
continue |
|
554 |
attr = rschema.type |
|
555 |
if attr == 'eid': |
|
556 |
continue |
|
557 |
# password retreival is blocked at the repository server level |
|
558 |
if not self.req.user.matching_groups(rschema.get_groups('read')) \ |
|
559 |
or attrschema.type == 'Password': |
|
560 |
self[attr] = None |
|
561 |
continue |
|
562 |
yield attr |
|
1474 | 563 |
|
0 | 564 |
def complete(self, attributes=None, skip_bytes=True): |
565 |
"""complete this entity by adding missing attributes (i.e. query the |
|
566 |
repository to fill the entity) |
|
567 |
||
568 |
:type skip_bytes: bool |
|
569 |
:param skip_bytes: |
|
570 |
if true, attribute of type Bytes won't be considered |
|
571 |
""" |
|
572 |
assert self.has_eid() |
|
573 |
varmaker = rqlvar_maker() |
|
574 |
V = varmaker.next() |
|
575 |
rql = ['WHERE %s eid %%(x)s' % V] |
|
576 |
selected = [] |
|
577 |
for attr in (attributes or self.to_complete_attributes(skip_bytes)): |
|
578 |
# if attribute already in entity, nothing to do |
|
579 |
if self.has_key(attr): |
|
580 |
continue |
|
581 |
# case where attribute must be completed, but is not yet in entity |
|
582 |
var = varmaker.next() |
|
583 |
rql.append('%s %s %s' % (V, attr, var)) |
|
584 |
selected.append((attr, var)) |
|
585 |
# +1 since this doen't include the main variable |
|
586 |
lastattr = len(selected) + 1 |
|
587 |
if attributes is None: |
|
588 |
# fetch additional relations (restricted to 0..1 relations) |
|
589 |
for rschema, role in self.to_complete_relations(): |
|
590 |
rtype = rschema.type |
|
591 |
if self.relation_cached(rtype, role): |
|
592 |
continue |
|
593 |
var = varmaker.next() |
|
594 |
if role == 'subject': |
|
595 |
targettype = rschema.objects(self.e_schema)[0] |
|
596 |
card = rschema.rproperty(self.e_schema, targettype, |
|
597 |
'cardinality')[0] |
|
598 |
if card == '1': |
|
599 |
rql.append('%s %s %s' % (V, rtype, var)) |
|
600 |
else: # '?" |
|
601 |
rql.append('%s %s %s?' % (V, rtype, var)) |
|
602 |
else: |
|
603 |
targettype = rschema.subjects(self.e_schema)[1] |
|
604 |
card = rschema.rproperty(self.e_schema, targettype, |
|
605 |
'cardinality')[1] |
|
606 |
if card == '1': |
|
607 |
rql.append('%s %s %s' % (var, rtype, V)) |
|
608 |
else: # '?" |
|
609 |
rql.append('%s? %s %s' % (var, rtype, V)) |
|
610 |
assert card in '1?', '%s %s %s %s' % (self.e_schema, rtype, |
|
611 |
role, card) |
|
612 |
selected.append(((rtype, role), var)) |
|
613 |
if selected: |
|
614 |
# select V, we need it as the left most selected variable |
|
615 |
# if some outer join are included to fetch inlined relations |
|
616 |
rql = 'Any %s,%s %s' % (V, ','.join(var for attr, var in selected), |
|
617 |
','.join(rql)) |
|
618 |
execute = getattr(self.req, 'unsafe_execute', self.req.execute) |
|
619 |
rset = execute(rql, {'x': self.eid}, 'x', build_descr=False)[0] |
|
620 |
# handle attributes |
|
621 |
for i in xrange(1, lastattr): |
|
622 |
self[str(selected[i-1][0])] = rset[i] |
|
623 |
# handle relations |
|
624 |
for i in xrange(lastattr, len(rset)): |
|
625 |
rtype, x = selected[i-1][0] |
|
626 |
value = rset[i] |
|
627 |
if value is None: |
|
628 |
rrset = ResultSet([], rql, {'x': self.eid}) |
|
629 |
self.req.decorate_rset(rrset) |
|
630 |
else: |
|
631 |
rrset = self.req.eid_rset(value) |
|
632 |
self.set_related_cache(rtype, x, rrset) |
|
1474 | 633 |
|
0 | 634 |
def get_value(self, name): |
635 |
"""get value for the attribute relation <name>, query the repository |
|
636 |
to get the value if necessary. |
|
637 |
||
638 |
:type name: str |
|
639 |
:param name: name of the attribute to get |
|
640 |
""" |
|
641 |
try: |
|
642 |
value = self[name] |
|
643 |
except KeyError: |
|
644 |
if not self.is_saved(): |
|
645 |
return None |
|
646 |
rql = "Any A WHERE X eid %%(x)s, X %s A" % name |
|
647 |
# XXX should we really use unsafe_execute here?? |
|
648 |
execute = getattr(self.req, 'unsafe_execute', self.req.execute) |
|
649 |
try: |
|
650 |
rset = execute(rql, {'x': self.eid}, 'x') |
|
651 |
except Unauthorized: |
|
652 |
self[name] = value = None |
|
653 |
else: |
|
654 |
assert rset.rowcount <= 1, (self, rql, rset.rowcount) |
|
655 |
try: |
|
656 |
self[name] = value = rset.rows[0][0] |
|
657 |
except IndexError: |
|
658 |
# probably a multisource error |
|
659 |
self.critical("can't get value for attribute %s of entity with eid %s", |
|
660 |
name, self.eid) |
|
661 |
if self.e_schema.destination(name) == 'String': |
|
662 |
self[name] = value = self.req._('unaccessible') |
|
663 |
else: |
|
664 |
self[name] = value = None |
|
665 |
return value |
|
666 |
||
667 |
def related(self, rtype, role='subject', limit=None, entities=False): |
|
668 |
"""returns a resultset of related entities |
|
1474 | 669 |
|
0 | 670 |
:param role: is the role played by 'self' in the relation ('subject' or 'object') |
671 |
:param limit: resultset's maximum size |
|
672 |
:param entities: if True, the entites are returned; if False, a result set is returned |
|
673 |
""" |
|
674 |
try: |
|
675 |
return self.related_cache(rtype, role, entities, limit) |
|
676 |
except KeyError: |
|
677 |
pass |
|
678 |
assert self.has_eid() |
|
679 |
rql = self.related_rql(rtype, role) |
|
680 |
rset = self.req.execute(rql, {'x': self.eid}, 'x') |
|
681 |
self.set_related_cache(rtype, role, rset) |
|
682 |
return self.related(rtype, role, limit, entities) |
|
683 |
||
684 |
def related_rql(self, rtype, role='subject'): |
|
685 |
rschema = self.schema[rtype] |
|
686 |
if role == 'subject': |
|
687 |
targettypes = rschema.objects(self.e_schema) |
|
688 |
restriction = 'E eid %%(x)s, E %s X' % rtype |
|
689 |
card = greater_card(rschema, (self.e_schema,), targettypes, 0) |
|
690 |
else: |
|
691 |
targettypes = rschema.subjects(self.e_schema) |
|
692 |
restriction = 'E eid %%(x)s, X %s E' % rtype |
|
693 |
card = greater_card(rschema, targettypes, (self.e_schema,), 1) |
|
694 |
if len(targettypes) > 1: |
|
413
a7366dd3c33c
fix bug in entity.related_rql(): fetch_attr list / fetchorder weren't computed correctly
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
397
diff
changeset
|
695 |
fetchattrs_list = [] |
0 | 696 |
for ttype in targettypes: |
697 |
etypecls = self.vreg.etype_class(ttype) |
|
413
a7366dd3c33c
fix bug in entity.related_rql(): fetch_attr list / fetchorder weren't computed correctly
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
397
diff
changeset
|
698 |
fetchattrs_list.append(set(etypecls.fetch_attrs)) |
a7366dd3c33c
fix bug in entity.related_rql(): fetch_attr list / fetchorder weren't computed correctly
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
397
diff
changeset
|
699 |
fetchattrs = reduce(set.intersection, fetchattrs_list) |
0 | 700 |
rql = etypecls.fetch_rql(self.req.user, [restriction], fetchattrs, |
701 |
settype=False) |
|
702 |
else: |
|
703 |
etypecls = self.vreg.etype_class(targettypes[0]) |
|
704 |
rql = etypecls.fetch_rql(self.req.user, [restriction], settype=False) |
|
705 |
# optimisation: remove ORDERBY if cardinality is 1 or ? (though |
|
706 |
# greater_card return 1 for those both cases) |
|
707 |
if card == '1': |
|
708 |
if ' ORDERBY ' in rql: |
|
709 |
rql = '%s WHERE %s' % (rql.split(' ORDERBY ', 1)[0], |
|
710 |
rql.split(' WHERE ', 1)[1]) |
|
711 |
elif not ' ORDERBY ' in rql: |
|
712 |
args = tuple(rql.split(' WHERE ', 1)) |
|
713 |
rql = '%s ORDERBY Z DESC WHERE X modification_date Z, %s' % args |
|
714 |
return rql |
|
1474 | 715 |
|
0 | 716 |
# generic vocabulary methods ############################################## |
717 |
||
1008
f54b4309a3f5
bw compat for vocabulary using new form
sylvain.thenault@logilab.fr
parents:
985
diff
changeset
|
718 |
@obsolete('see new form api') |
0 | 719 |
def vocabulary(self, rtype, role='subject', limit=None): |
720 |
"""vocabulary functions must return a list of couples |
|
721 |
(label, eid) that will typically be used to fill the |
|
722 |
edition view's combobox. |
|
1474 | 723 |
|
0 | 724 |
If `eid` is None in one of these couples, it should be |
725 |
interpreted as a separator in case vocabulary results are grouped |
|
726 |
""" |
|
1008
f54b4309a3f5
bw compat for vocabulary using new form
sylvain.thenault@logilab.fr
parents:
985
diff
changeset
|
727 |
from cubicweb.web.form import EntityFieldsForm |
f54b4309a3f5
bw compat for vocabulary using new form
sylvain.thenault@logilab.fr
parents:
985
diff
changeset
|
728 |
from logilab.common.testlib import mock_object |
f54b4309a3f5
bw compat for vocabulary using new form
sylvain.thenault@logilab.fr
parents:
985
diff
changeset
|
729 |
form = EntityFieldsForm(self.req, entity=self) |
f54b4309a3f5
bw compat for vocabulary using new form
sylvain.thenault@logilab.fr
parents:
985
diff
changeset
|
730 |
field = mock_object(name=rtype, role=role) |
1031
1a89683cb687
restore limit on form_field_vocabulary, actually used
sylvain.thenault@logilab.fr
parents:
1008
diff
changeset
|
731 |
return form.form_field_vocabulary(field, limit) |
1474 | 732 |
|
0 | 733 |
def unrelated_rql(self, rtype, targettype, role, ordermethod=None, |
734 |
vocabconstraints=True): |
|
735 |
"""build a rql to fetch `targettype` entities unrelated to this entity |
|
736 |
using (rtype, role) relation |
|
737 |
""" |
|
738 |
ordermethod = ordermethod or 'fetch_unrelated_order' |
|
739 |
if isinstance(rtype, basestring): |
|
740 |
rtype = self.schema.rschema(rtype) |
|
741 |
if role == 'subject': |
|
742 |
evar, searchedvar = 'S', 'O' |
|
743 |
subjtype, objtype = self.e_schema, targettype |
|
744 |
else: |
|
745 |
searchedvar, evar = 'S', 'O' |
|
746 |
objtype, subjtype = self.e_schema, targettype |
|
747 |
if self.has_eid(): |
|
748 |
restriction = ['NOT S %s O' % rtype, '%s eid %%(x)s' % evar] |
|
749 |
else: |
|
750 |
restriction = [] |
|
751 |
constraints = rtype.rproperty(subjtype, objtype, 'constraints') |
|
752 |
if vocabconstraints: |
|
753 |
# RQLConstraint is a subclass for RQLVocabularyConstraint, so they |
|
754 |
# will be included as well |
|
755 |
restriction += [cstr.restriction for cstr in constraints |
|
756 |
if isinstance(cstr, RQLVocabularyConstraint)] |
|
757 |
else: |
|
758 |
restriction += [cstr.restriction for cstr in constraints |
|
759 |
if isinstance(cstr, RQLConstraint)] |
|
760 |
etypecls = self.vreg.etype_class(targettype) |
|
761 |
rql = etypecls.fetch_rql(self.req.user, restriction, |
|
762 |
mainvar=searchedvar, ordermethod=ordermethod) |
|
763 |
# ensure we have an order defined |
|
764 |
if not ' ORDERBY ' in rql: |
|
765 |
before, after = rql.split(' WHERE ', 1) |
|
766 |
rql = '%s ORDERBY %s WHERE %s' % (before, searchedvar, after) |
|
767 |
return rql |
|
1474 | 768 |
|
0 | 769 |
def unrelated(self, rtype, targettype, role='subject', limit=None, |
770 |
ordermethod=None): |
|
771 |
"""return a result set of target type objects that may be related |
|
772 |
by a given relation, with self as subject or object |
|
773 |
""" |
|
774 |
rql = self.unrelated_rql(rtype, targettype, role, ordermethod) |
|
775 |
if limit is not None: |
|
776 |
before, after = rql.split(' WHERE ', 1) |
|
777 |
rql = '%s LIMIT %s WHERE %s' % (before, limit, after) |
|
778 |
if self.has_eid(): |
|
779 |
return self.req.execute(rql, {'x': self.eid}) |
|
780 |
return self.req.execute(rql) |
|
1474 | 781 |
|
0 | 782 |
# relations cache handling ################################################ |
1474 | 783 |
|
0 | 784 |
def relation_cached(self, rtype, role): |
785 |
"""return true if the given relation is already cached on the instance |
|
786 |
""" |
|
787 |
return '%s_%s' % (rtype, role) in self._related_cache |
|
1474 | 788 |
|
0 | 789 |
def related_cache(self, rtype, role, entities=True, limit=None): |
790 |
"""return values for the given relation if it's cached on the instance, |
|
791 |
else raise `KeyError` |
|
792 |
""" |
|
793 |
res = self._related_cache['%s_%s' % (rtype, role)][entities] |
|
794 |
if limit: |
|
795 |
if entities: |
|
796 |
res = res[:limit] |
|
797 |
else: |
|
798 |
res = res.limit(limit) |
|
799 |
return res |
|
1474 | 800 |
|
0 | 801 |
def set_related_cache(self, rtype, role, rset, col=0): |
802 |
"""set cached values for the given relation""" |
|
803 |
if rset: |
|
804 |
related = list(rset.entities(col)) |
|
805 |
rschema = self.schema.rschema(rtype) |
|
806 |
if role == 'subject': |
|
807 |
rcard = rschema.rproperty(self.e_schema, related[0].e_schema, |
|
808 |
'cardinality')[1] |
|
809 |
target = 'object' |
|
810 |
else: |
|
811 |
rcard = rschema.rproperty(related[0].e_schema, self.e_schema, |
|
812 |
'cardinality')[0] |
|
813 |
target = 'subject' |
|
814 |
if rcard in '?1': |
|
815 |
for rentity in related: |
|
816 |
rentity._related_cache['%s_%s' % (rtype, target)] = (self.as_rset(), [self]) |
|
817 |
else: |
|
818 |
related = [] |
|
819 |
self._related_cache['%s_%s' % (rtype, role)] = (rset, related) |
|
1474 | 820 |
|
0 | 821 |
def clear_related_cache(self, rtype=None, role=None): |
822 |
"""clear cached values for the given relation or the entire cache if |
|
823 |
no relation is given |
|
824 |
""" |
|
825 |
if rtype is None: |
|
826 |
self._related_cache = {} |
|
827 |
else: |
|
828 |
assert role |
|
829 |
self._related_cache.pop('%s_%s' % (rtype, role), None) |
|
1474 | 830 |
|
0 | 831 |
# raw edition utilities ################################################### |
1474 | 832 |
|
0 | 833 |
def set_attributes(self, **kwargs): |
834 |
assert kwargs |
|
835 |
relations = [] |
|
836 |
for key in kwargs: |
|
837 |
relations.append('X %s %%(%s)s' % (key, key)) |
|
397
cf577e26f924
don't introduce a spurious 'x' key in the entity-as dict
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
237
diff
changeset
|
838 |
# update current local object |
cf577e26f924
don't introduce a spurious 'x' key in the entity-as dict
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
237
diff
changeset
|
839 |
self.update(kwargs) |
cf577e26f924
don't introduce a spurious 'x' key in the entity-as dict
Aurelien Campeas <aurelien.campeas@logilab.fr>
parents:
237
diff
changeset
|
840 |
# and now update the database |
0 | 841 |
kwargs['x'] = self.eid |
842 |
self.req.execute('SET %s WHERE X eid %%(x)s' % ','.join(relations), |
|
843 |
kwargs, 'x') |
|
1474 | 844 |
|
0 | 845 |
def delete(self): |
846 |
assert self.has_eid(), self.eid |
|
847 |
self.req.execute('DELETE %s X WHERE X eid %%(x)s' % self.e_schema, |
|
848 |
{'x': self.eid}) |
|
1474 | 849 |
|
0 | 850 |
# server side utilities ################################################### |
1474 | 851 |
|
0 | 852 |
def set_defaults(self): |
853 |
"""set default values according to the schema""" |
|
854 |
self._default_set = set() |
|
855 |
for attr, value in self.e_schema.defaults(): |
|
856 |
if not self.has_key(attr): |
|
857 |
self[str(attr)] = value |
|
858 |
self._default_set.add(attr) |
|
859 |
||
860 |
def check(self, creation=False): |
|
861 |
"""check this entity against its schema. Only final relation |
|
862 |
are checked here, constraint on actual relations are checked in hooks |
|
863 |
""" |
|
864 |
# necessary since eid is handled specifically and yams require it to be |
|
865 |
# in the dictionary |
|
866 |
if self.req is None: |
|
867 |
_ = unicode |
|
868 |
else: |
|
869 |
_ = self.req._ |
|
870 |
self.e_schema.check(self, creation=creation, _=_) |
|
871 |
||
872 |
def fti_containers(self, _done=None): |
|
873 |
if _done is None: |
|
874 |
_done = set() |
|
875 |
_done.add(self.eid) |
|
876 |
containers = tuple(self.e_schema.fulltext_containers()) |
|
877 |
if containers: |
|
476
62968fa8845c
yield self if no ft container found
sylvain.thenault@logilab.fr
parents:
475
diff
changeset
|
878 |
yielded = False |
0 | 879 |
for rschema, target in containers: |
880 |
if target == 'object': |
|
881 |
targets = getattr(self, rschema.type) |
|
882 |
else: |
|
883 |
targets = getattr(self, 'reverse_%s' % rschema) |
|
884 |
for entity in targets: |
|
885 |
if entity.eid in _done: |
|
886 |
continue |
|
887 |
for container in entity.fti_containers(_done): |
|
888 |
yield container |
|
476
62968fa8845c
yield self if no ft container found
sylvain.thenault@logilab.fr
parents:
475
diff
changeset
|
889 |
yielded = True |
62968fa8845c
yield self if no ft container found
sylvain.thenault@logilab.fr
parents:
475
diff
changeset
|
890 |
if not yielded: |
62968fa8845c
yield self if no ft container found
sylvain.thenault@logilab.fr
parents:
475
diff
changeset
|
891 |
yield self |
0 | 892 |
else: |
893 |
yield self |
|
1474 | 894 |
|
0 | 895 |
def get_words(self): |
896 |
"""used by the full text indexer to get words to index |
|
897 |
||
898 |
this method should only be used on the repository side since it depends |
|
899 |
on the indexer package |
|
1474 | 900 |
|
0 | 901 |
:rtype: list |
902 |
:return: the list of indexable word of this entity |
|
903 |
""" |
|
904 |
from indexer.query_objects import tokenize |
|
905 |
words = [] |
|
906 |
for rschema in self.e_schema.indexable_attributes(): |
|
907 |
try: |
|
908 |
value = self.printable_value(rschema, format='text/plain') |
|
1132 | 909 |
except TransformError: |
0 | 910 |
continue |
911 |
except: |
|
912 |
self.exception("can't add value of %s to text index for entity %s", |
|
913 |
rschema, self.eid) |
|
914 |
continue |
|
915 |
if value: |
|
916 |
words += tokenize(value) |
|
1474 | 917 |
|
0 | 918 |
for rschema, role in self.e_schema.fulltext_relations(): |
919 |
if role == 'subject': |
|
920 |
for entity in getattr(self, rschema.type): |
|
921 |
words += entity.get_words() |
|
922 |
else: # if role == 'object': |
|
923 |
for entity in getattr(self, 'reverse_%s' % rschema.type): |
|
924 |
words += entity.get_words() |
|
925 |
return words |
|
926 |
||
927 |
||
928 |
# attribute and relation descriptors ########################################## |
|
929 |
||
930 |
class Attribute(object): |
|
931 |
"""descriptor that controls schema attribute access""" |
|
932 |
||
933 |
def __init__(self, attrname): |
|
934 |
assert attrname != 'eid' |
|
935 |
self._attrname = attrname |
|
936 |
||
937 |
def __get__(self, eobj, eclass): |
|
938 |
if eobj is None: |
|
939 |
return self |
|
940 |
return eobj.get_value(self._attrname) |
|
941 |
||
942 |
def __set__(self, eobj, value): |
|
943 |
# XXX bw compat |
|
944 |
# would be better to generate UPDATE queries than the current behaviour |
|
945 |
eobj.warning("deprecated usage, don't use 'entity.attr = val' notation)") |
|
946 |
eobj[self._attrname] = value |
|
947 |
||
948 |
||
949 |
class Relation(object): |
|
950 |
"""descriptor that controls schema relation access""" |
|
951 |
_role = None # for pylint |
|
952 |
||
953 |
def __init__(self, rschema): |
|
954 |
self._rschema = rschema |
|
955 |
self._rtype = rschema.type |
|
956 |
||
957 |
def __get__(self, eobj, eclass): |
|
958 |
if eobj is None: |
|
959 |
raise AttributeError('%s cannot be only be accessed from instances' |
|
960 |
% self._rtype) |
|
961 |
return eobj.related(self._rtype, self._role, entities=True) |
|
1474 | 962 |
|
0 | 963 |
def __set__(self, eobj, value): |
964 |
raise NotImplementedError |
|
965 |
||
966 |
||
967 |
class SubjectRelation(Relation): |
|
968 |
"""descriptor that controls schema relation access""" |
|
969 |
_role = 'subject' |
|
1474 | 970 |
|
0 | 971 |
class ObjectRelation(Relation): |
972 |
"""descriptor that controls schema relation access""" |
|
973 |
_role = 'object' |
|
974 |
||
975 |
from logging import getLogger |
|
976 |
from cubicweb import set_log_methods |
|
977 |
set_log_methods(Entity, getLogger('cubicweb.entity')) |