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