entity.py 60.7 KB
Newer Older
1
# copyright 2003-2014 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
2
3
4
5
6
7
8
9
10
# contact http://www.logilab.fr/ -- mailto:contact@logilab.fr
#
# This file is part of CubicWeb.
#
# CubicWeb is free software: you can redistribute it and/or modify it under the
# terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 2.1 of the License, or (at your option)
# any later version.
#
11
# CubicWeb is distributed in the hope that it will be useful, but WITHOUT
12
13
14
15
16
17
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License along
# with CubicWeb.  If not, see <http://www.gnu.org/licenses/>.
18
"""Base class for entity objects manipulated in clients"""
Adrien Di Mascio's avatar
Adrien Di Mascio committed
19
20
21

__docformat__ = "restructuredtext en"

22
23
from warnings import warn

24
from six import text_type, string_types, integer_types
25
26
from six.moves import range

Adrien Di Mascio's avatar
Adrien Di Mascio committed
27
from logilab.common.decorators import cached
28
from logilab.common.deprecation import deprecated
29
from logilab.common.registry import yes
Pierre-Yves David's avatar
Pierre-Yves David committed
30
from logilab.mtconverter import TransformData, xml_escape
31

Adrien Di Mascio's avatar
Adrien Di Mascio committed
32
from rql.utils import rqlvar_maker
33
34
35
from rql.stmts import Select
from rql.nodes import (Not, VariableRef, Constant, make_relation,
                       Relation as RqlRelation)
Adrien Di Mascio's avatar
Adrien Di Mascio committed
36

37
from cubicweb import Unauthorized, neg_role
38
from cubicweb.utils import support_args
Adrien Di Mascio's avatar
Adrien Di Mascio committed
39
from cubicweb.rset import ResultSet
40
from cubicweb.appobject import AppObject
41
42
from cubicweb.schema import (RQLVocabularyConstraint, RQLConstraint,
                             GeneratedConstraint)
43
from cubicweb.rqlrewrite import RQLRewriter
44

45
from cubicweb.uilib import soup2xhtml
Sylvain Thénault's avatar
Sylvain Thénault committed
46
from cubicweb.mttransforms import ENGINE
Adrien Di Mascio's avatar
Adrien Di Mascio committed
47
48
49
50
51
52

_marker = object()

def greater_card(rschema, subjtypes, objtypes, index):
    for subjtype in subjtypes:
        for objtype in objtypes:
Sylvain Thénault's avatar
Sylvain Thénault committed
53
            card = rschema.rdef(subjtype, objtype).cardinality[index]
Adrien Di Mascio's avatar
Adrien Di Mascio committed
54
55
56
57
            if card in '+*':
                return card
    return '1'

58
59
60
61
def can_use_rest_path(value):
    """return True if value can be used at the end of a Rest URL path"""
    if value is None:
        return False
62
    value = text_type(value)
63
64
65
66
67
68
    # the check for ?, /, & are to prevent problems when running
    # behind Apache mod_proxy
    if value == u'' or u'?' in value or u'/' in value or u'&' in value:
        return False
    return True

69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
def rel_vars(rel):
    return ((isinstance(rel.children[0], VariableRef)
             and rel.children[0].variable or None),
            (isinstance(rel.children[1].children[0], VariableRef)
             and rel.children[1].children[0].variable or None)
            )

def rel_matches(rel, rtype, role, varname, operator='='):
    if rel.r_type == rtype and rel.children[1].operator == operator:
        same_role_var_idx = 0 if role == 'subject' else 1
        variables = rel_vars(rel)
        if variables[same_role_var_idx].name == varname:
            return variables[1 - same_role_var_idx]

def build_cstr_with_linkto_infos(cstr, args, searchedvar, evar,
                                 lt_infos, eidvars):
    """restrict vocabulary as much as possible in entity creation,
    based on infos provided by __linkto form param.

    Example based on following schema:

      class works_in(RelationDefinition):
          subject = 'CWUser'
          object = 'Lab'
          cardinality = '1*'
          constraints = [RQLConstraint('S in_group G, O welcomes G')]

      class welcomes(RelationDefinition):
          subject = 'Lab'
          object = 'CWGroup'

    If you create a CWUser in the "scientists" CWGroup you can show
    only the labs that welcome them using :

      lt_infos = {('in_group', 'subject'): 321}

    You get following restriction : 'O welcomes G, G eid 321'

    """
    st = cstr.snippet_rqlst.copy()
    # replace relations in ST by eid infos from linkto where possible
110
    for (info_rtype, info_role), eids in lt_infos.items():
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
        eid = eids[0] # NOTE: we currently assume a pruned lt_info with only 1 eid
        for rel in st.iget_nodes(RqlRelation):
            targetvar = rel_matches(rel, info_rtype, info_role, evar.name)
            if targetvar is not None:
                if targetvar.name in eidvars:
                    rel.parent.remove(rel)
                else:
                    eidrel = make_relation(
                        targetvar, 'eid', (targetvar.name, 'Substitute'),
                        Constant)
                    rel.parent.replace(rel, eidrel)
                    args[targetvar.name] = eid
                    eidvars.add(targetvar.name)
    # if modified ST still contains evar references we must discard the
    # constraint, otherwise evar is unknown in the final rql query which can
    # lead to a SQL table cartesian product and multiple occurences of solutions
    evarname = evar.name
    for rel in st.iget_nodes(RqlRelation):
        for variable in rel_vars(rel):
            if variable and evarname == variable.name:
                return
    # else insert snippets into the global tree
    return GeneratedConstraint(st, cstr.mainvars - set(evarname))

def pruned_lt_info(eschema, lt_infos):
    pruned = {}
137
    for (lt_rtype, lt_role), eids in lt_infos.items():
138
139
140
141
142
143
144
145
146
147
        # we can only use lt_infos describing relation with a cardinality
        # of value 1 towards the linked entity
        if not len(eids) == 1:
            continue
        lt_card = eschema.rdef(lt_rtype, lt_role).cardinality[
            0 if lt_role == 'subject' else 1]
        if lt_card not in '?1':
            continue
        pruned[(lt_rtype, lt_role)] = eids
    return pruned
148

149

150
class Entity(AppObject):
151
152
    """an entity instance has e_schema automagically set on
    the class and instances has access to their issuing cursor.
153

154
    A property is set for each attribute and relation on each entity's type
Sylvain Thénault's avatar
Sylvain Thénault committed
155
    class. Becare that among attributes, 'eid' is *NEVER* stored in the
156
157
    dict containment (which acts as a cache for other attributes dynamically
    fetched)
Adrien Di Mascio's avatar
Adrien Di Mascio committed
158
159
160
161

    :type e_schema: `cubicweb.schema.EntitySchema`
    :ivar e_schema: the entity's schema

162
163
164
165
    :type rest_attr: str
    :cvar rest_attr: indicates which attribute should be used to build REST urls
       If `None` is specified (the default), the first unique attribute will
       be used ('eid' if none found)
166

167
168
    :type cw_skip_copy_for: list
    :cvar cw_skip_copy_for: a list of couples (rtype, role) for each relation
169
170
171
       that should be skipped when copying this kind of entity. Note that some
       relations such as composite relations or relations that have '?1' as
       object cardinality are always skipped.
Adrien Di Mascio's avatar
Adrien Di Mascio committed
172
173
    """
    __registry__ = 'etypes'
174
    __select__ = yes()
175

176
    # class attributes that must be set in class definition
Adrien Di Mascio's avatar
Adrien Di Mascio committed
177
    rest_attr = None
178
    fetch_attrs = None
179
180
    skip_copy_for = () # bw compat (< 3.14), use cw_skip_copy_for instead
    cw_skip_copy_for = [('in_state', 'subject')]
181
182
    # class attributes set automatically at registration time
    e_schema = None
183

Adrien Di Mascio's avatar
Adrien Di Mascio committed
184
    @classmethod
185
    def __initialize__(cls, schema):
Adrien Di Mascio's avatar
Adrien Di Mascio committed
186
187
188
        """initialize a specific entity class by adding descriptors to access
        entity type's attributes and relations
        """
189
        etype = cls.__regid__
Adrien Di Mascio's avatar
Adrien Di Mascio committed
190
        assert etype != 'Any', etype
191
        cls.e_schema = eschema = schema.eschema(etype)
Adrien Di Mascio's avatar
Adrien Di Mascio committed
192
        for rschema, _ in eschema.attribute_definitions():
193
            if rschema.type == 'eid':
Adrien Di Mascio's avatar
Adrien Di Mascio committed
194
                continue
195
            setattr(cls, rschema.type, Attribute(rschema.type))
Adrien Di Mascio's avatar
Adrien Di Mascio committed
196
        mixins = []
197
198
        for rschema, _, role in eschema.relation_definitions():
            if role == 'subject':
199
                attr = rschema.type
Adrien Di Mascio's avatar
Adrien Di Mascio committed
200
            else:
201
                attr = 'reverse_%s' % rschema.type
202
            setattr(cls, attr, Relation(rschema, role))
203

204
    fetch_attrs = ('modification_date',)
205

206
    @classmethod
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
    def cw_fetch_order(cls, select, attr, var):
        """This class method may be used to control sort order when multiple
        entities of this type are fetched through ORM methods. Its arguments
        are:

        * `select`, the RQL syntax tree

        * `attr`, the attribute being watched

        * `var`, the variable through which this attribute's value may be
          accessed in the query

        When you want to do some sorting on the given attribute, you should
        modify the syntax tree accordingly. For instance:

        .. sourcecode:: python

          from rql import nodes

          class Version(AnyEntity):
              __regid__ = 'Version'

              fetch_attrs = ('num', 'description', 'in_state')

              @classmethod
              def cw_fetch_order(cls, select, attr, var):
                  if attr == 'num':
                      func = nodes.Function('version_sort_value')
                      func.append(nodes.variable_ref(var))
                      sterm = nodes.SortTerm(func, asc=False)
                      select.add_sort_term(sterm)

        The default implementation call
        :meth:`~cubicweb.entity.Entity.cw_fetch_unrelated_order`
241
        """
242
        cls.cw_fetch_unrelated_order(select, attr, var)
243
244

    @classmethod
245
246
247
    def cw_fetch_unrelated_order(cls, select, attr, var):
        """This class method may be used to control sort order when multiple entities of
        this type are fetched to use in edition (e.g. propose them to create a
248
        new relation on an edited entity).
249
250
251
252
253
254

        See :meth:`~cubicweb.entity.Entity.cw_fetch_unrelated_order` for a
        description of its arguments and usage.

        By default entities will be listed on their modification date descending,
        i.e. you'll get entities recently modified first.
255
256
        """
        if attr == 'modification_date':
257
            select.add_sort_var(var, asc=False)
258

Adrien Di Mascio's avatar
Adrien Di Mascio committed
259
260
261
    @classmethod
    def fetch_rql(cls, user, restriction=None, fetchattrs=None, mainvar='X',
                  settype=True, ordermethod='fetch_order'):
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
        st = cls.fetch_rqlst(user, mainvar=mainvar, fetchattrs=fetchattrs,
                             settype=settype, ordermethod=ordermethod)
        rql = st.as_string()
        if restriction:
            # cannot use RQLRewriter API to insert 'X rtype %(x)s' restriction
            warn('[3.14] fetch_rql: use of `restriction` parameter is '
                 'deprecated, please use fetch_rqlst and supply a syntax'
                 'tree with your restriction instead', DeprecationWarning)
            insert = ' WHERE ' + ','.join(restriction)
            if ' WHERE ' in rql:
                select, where = rql.split(' WHERE ', 1)
                rql = select + insert + ',' + where
            else:
                rql += insert
        return rql

    @classmethod
    def fetch_rqlst(cls, user, select=None, mainvar='X', fetchattrs=None,
                    settype=True, ordermethod='fetch_order'):
        if select is None:
            select = Select()
            mainvar = select.get_variable(mainvar)
            select.add_selected(mainvar)
285
        elif isinstance(mainvar, string_types):
286
287
288
289
290
            assert mainvar in select.defined_vars
            mainvar = select.get_variable(mainvar)
        # eases string -> syntax tree test transition: please remove once stable
        select._varmaker = rqlvar_maker(defined=select.defined_vars,
                                        aliases=select.aliases, index=26)
Adrien Di Mascio's avatar
Adrien Di Mascio committed
291
        if settype:
292
293
294
295
            rel = select.add_type_restriction(mainvar, cls.__regid__)
            # should use 'is_instance_of' instead of 'is' so we retrieve
            # subclasses instances as well
            rel.r_type = 'is_instance_of'
Adrien Di Mascio's avatar
Adrien Di Mascio committed
296
297
        if fetchattrs is None:
            fetchattrs = cls.fetch_attrs
298
299
        cls._fetch_restrictions(mainvar, select, fetchattrs, user, ordermethod)
        return select
300

301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
    @classmethod
    def _fetch_ambiguous_rtypes(cls, select, var, fetchattrs, subjtypes, schema):
        """find rtypes in `fetchattrs` that relate different subject etypes
        taken from (`subjtypes`) to different target etypes; these so called
        "ambiguous" relations, are added directly to the `select` syntax tree
        selection but removed from `fetchattrs` to avoid the fetch recursion
        because we have to choose only one targettype for the recursion and
        adding its own fetch attrs to the selection -when we recurse- would
        filter out the other possible target types from the result set
        """
        for attr in fetchattrs.copy():
            rschema = schema.rschema(attr)
            if rschema.final:
                continue
            ttypes = None
            for subjtype in subjtypes:
                cur_ttypes = set(rschema.objects(subjtype))
                if ttypes is None:
                    ttypes = cur_ttypes
                elif cur_ttypes != ttypes:
                    # we found an ambiguous relation: remove it from fetchattrs
                    fetchattrs.remove(attr)
                    # ... and add it to the selection
                    targetvar = select.make_variable()
                    select.add_selected(targetvar)
                    rel = make_relation(var, attr, (targetvar,), VariableRef)
                    select.add_restriction(rel)
                    break

Adrien Di Mascio's avatar
Adrien Di Mascio committed
330
    @classmethod
331
332
    def _fetch_restrictions(cls, mainvar, select, fetchattrs,
                            user, ordermethod='fetch_order', visited=None):
Adrien Di Mascio's avatar
Adrien Di Mascio committed
333
334
335
336
337
338
339
340
        eschema = cls.e_schema
        if visited is None:
            visited = set((eschema.type,))
        elif eschema.type in visited:
            # avoid infinite recursion
            return
        else:
            visited.add(eschema.type)
341
        for attr in sorted(fetchattrs):
Adrien Di Mascio's avatar
Adrien Di Mascio committed
342
            try:
343
                rschema = eschema.subjrels[attr]
Adrien Di Mascio's avatar
Adrien Di Mascio committed
344
345
            except KeyError:
                cls.warning('skipping fetch_attr %s defined in %s (not found in schema)',
346
                            attr, cls.__regid__)
Adrien Di Mascio's avatar
Adrien Di Mascio committed
347
                continue
348
349
            # XXX takefirst=True to remove warning triggered by ambiguous inlined relations
            rdef = eschema.rdef(attr, takefirst=True)
Sylvain Thénault's avatar
Sylvain Thénault committed
350
            if not user.matching_groups(rdef.get_groups('read')):
Adrien Di Mascio's avatar
Adrien Di Mascio committed
351
                continue
352
353
354
355
356
357
358
359
360
            if rschema.final or rdef.cardinality[0] in '?1':
                var = select.make_variable()
                select.add_selected(var)
                rel = make_relation(mainvar, attr, (var,), VariableRef)
                select.add_restriction(rel)
            else:
                cls.warning('bad relation %s specified in fetch attrs for %s',
                            attr, cls)
                continue
361
            if not rschema.final:
362
363
364
365
                # XXX we need outer join in case the relation is not mandatory
                # (card == '?')  *or if the entity is being added*, since in
                # that case the relation may still be missing. As we miss this
                # later information here, systematically add it.
366
                rel.change_optional('right')
367
                targettypes = rschema.objects(eschema.type)
368
                vreg = user._cw.vreg  # XXX user._cw.vreg iiiirk
369
                etypecls = vreg['etypes'].etype_class(targettypes[0])
370
371
                if len(targettypes) > 1:
                    # find fetch_attrs common to all destination types
372
                    fetchattrs = vreg['etypes'].fetch_attrs(targettypes)
Sylvain Thénault's avatar
Sylvain Thénault committed
373
                    # ... and handle ambiguous relations
374
375
                    cls._fetch_ambiguous_rtypes(select, var, fetchattrs,
                                                targettypes, vreg.schema)
376
377
                else:
                    fetchattrs = etypecls.fetch_attrs
378
                etypecls._fetch_restrictions(var, select, fetchattrs,
379
                                             user, None, visited=visited)
380
            if ordermethod is not None:
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
                try:
                    cmeth = getattr(cls, ordermethod)
                    warn('[3.14] %s %s class method should be renamed to cw_%s'
                         % (cls.__regid__, ordermethod, ordermethod),
                         DeprecationWarning)
                except AttributeError:
                    cmeth = getattr(cls, 'cw_' + ordermethod)
                if support_args(cmeth, 'select'):
                    cmeth(select, attr, var)
                else:
                    warn('[3.14] %s should now take (select, attr, var) and '
                         'modify the syntax tree when desired instead of '
                         'returning something' % cmeth, DeprecationWarning)
                    orderterm = cmeth(attr, var.name)
                    if orderterm is not None:
                        try:
                            var, order = orderterm.split()
                        except ValueError:
                            if '(' in orderterm:
400
401
                                cls.error('ignore %s until %s is upgraded',
                                          orderterm, cmeth)
402
403
404
405
406
407
408
                                orderterm = None
                            elif not ' ' in orderterm.strip():
                                var = orderterm
                                order = 'ASC'
                        if orderterm is not None:
                            select.add_sort_var(select.get_variable(var),
                                                order=='ASC')
Adrien Di Mascio's avatar
Adrien Di Mascio committed
409

410
411
    @classmethod
    @cached
412
413
414
415
416
417
418
419
420
421
422
    def cw_rest_attr_info(cls):
        """this class method return an attribute name to be used in URL for
        entities of this type and a boolean flag telling if its value should be
        checked for uniqness.

        The attribute returned is, in order of priority:

        * class's `rest_attr` class attribute
        * an attribute defined as unique in the class'schema
        * 'eid'
        """
423
424
425
426
427
428
        mainattr, needcheck = 'eid', True
        if cls.rest_attr:
            mainattr = cls.rest_attr
            needcheck = not cls.e_schema.has_unique_values(mainattr)
        else:
            for rschema in cls.e_schema.subject_relations():
429
                if (rschema.final
430
                    and rschema not in ('eid', 'cwuri')
431
432
                    and cls.e_schema.has_unique_values(rschema)
                    and cls.e_schema.rdef(rschema.type).cardinality[0] == '1'):
433
434
435
436
437
438
439
                    mainattr = str(rschema)
                    needcheck = False
                    break
        if mainattr == 'eid':
            needcheck = False
        return mainattr, needcheck

440
    @classmethod
441
    def _cw_build_entity_query(cls, kwargs):
442
443
        relations = []
        restrictions = set()
444
        pendingrels = []
445
        eschema = cls.e_schema
446
        qargs = {}
447
        attrcache = {}
448
        for attr, value in kwargs.items():
449
450
451
452
453
            if attr.startswith('reverse_'):
                attr = attr[len('reverse_'):]
                role = 'object'
            else:
                role = 'subject'
454
            assert eschema.has_relation(attr, role), '%s %s not found on %s' % (attr, role, eschema)
455
            rschema = eschema.subjrels[attr] if role == 'subject' else eschema.objrels[attr]
456
            if not rschema.final and isinstance(value, (tuple, list, set, frozenset)):
457
458
459
                if len(value) == 0:
                    continue # avoid crash with empty IN clause
                elif len(value) == 1:
460
                    value = next(iter(value))
461
                else:
462
                    # prepare IN clause
463
                    pendingrels.append( (attr, role, value) )
464
                    continue
465
466
            if rschema.final: # attribute
                relations.append('X %s %%(%s)s' % (attr, attr))
467
468
                attrcache[attr] = value
            elif value is None:
469
                pendingrels.append( (attr, role, value) )
470
            else:
471
                rvar = attr.upper()
472
473
                if role == 'object':
                    relations.append('%s %s X' % (rvar, attr))
474
475
476
477
478
                else:
                    relations.append('X %s %s' % (attr, rvar))
                restriction = '%s eid %%(%s)s' % (rvar, attr)
                if not restriction in restrictions:
                    restrictions.add(restriction)
479
480
481
                if hasattr(value, 'eid'):
                    value = value.eid
            qargs[attr] = value
482
        rql = u''
483
        if relations:
484
            rql += ', '.join(relations)
485
        if restrictions:
486
            rql += ' WHERE %s' % ', '.join(restrictions)
487
        return rql, qargs, pendingrels, attrcache
488
489

    @classmethod
490
491
    def _cw_handle_pending_relations(cls, eid, pendingrels, execute):
        for attr, role, values in pendingrels:
492
493
            if role == 'object':
                restr = 'Y %s X' % attr
494
495
            else:
                restr = 'X %s Y' % attr
496
497
498
            if values is None:
                execute('DELETE %s WHERE X eid %%(x)s' % restr, {'x': eid})
                continue
499
            execute('SET %s WHERE X eid %%(x)s, Y eid IN (%s)' % (
500
                restr, ','.join(str(getattr(r, 'eid', r)) for r in values)),
501
502
503
504
505
506
507
508
                    {'x': eid}, build_descr=False)

    @classmethod
    def cw_instantiate(cls, execute, **kwargs):
        """add a new entity of this given type

        Example (in a shell session):

Jérôme Roy's avatar
Jérôme Roy committed
509
510
        >>> companycls = vreg['etypes'].etype_class('Company')
        >>> personcls = vreg['etypes'].etype_class('Person')
511
512
513
514
515
516
517
518
        >>> c = companycls.cw_instantiate(session.execute, name=u'Logilab')
        >>> p = personcls.cw_instantiate(session.execute, firstname=u'John', lastname=u'Doe',
        ...                              works_for=c)

        You can also set relations where the entity has 'object' role by
        prefixing the relation name by 'reverse_'. Also, relation values may be
        an entity or eid, a list of entities or eids.
        """
519
        rql, qargs, pendingrels, attrcache = cls._cw_build_entity_query(kwargs)
520
521
522
523
        if rql:
            rql = 'INSERT %s X: %s' % (cls.__regid__, rql)
        else:
            rql = 'INSERT %s X' % (cls.__regid__)
524
525
526
527
528
        try:
            created = execute(rql, qargs).get_entity(0, 0)
        except IndexError:
            raise Exception('could not create a %r with %r (%r)' %
                            (cls.__regid__, rql, qargs))
529
        created._cw_update_attr_cache(attrcache)
530
        cls._cw_handle_pending_relations(created.eid, pendingrels, execute)
531
532
        return created

533
    def __init__(self, req, rset=None, row=None, col=0):
534
        AppObject.__init__(self, req, rset=rset, row=row, col=col)
535
        self._cw_related_cache = {}
536
        self._cw_adapters_cache = {}
Adrien Di Mascio's avatar
Adrien Di Mascio committed
537
538
539
540
        if rset is not None:
            self.eid = rset[row][col]
        else:
            self.eid = None
541
        self._cw_is_saved = True
542
        self.cw_attr_cache = {}
543

Adrien Di Mascio's avatar
Adrien Di Mascio committed
544
545
    def __repr__(self):
        return '<Entity %s %s %s at %s>' % (
546
            self.e_schema, self.eid, list(self.cw_attr_cache), id(self))
Adrien Di Mascio's avatar
Adrien Di Mascio committed
547

548
    def __lt__(self, other):
549
        return NotImplemented
550
551

    def __eq__(self, other):
Rémi Cardona's avatar
Rémi Cardona committed
552
        if isinstance(self.eid, integer_types):
553
554
555
556
            return self.eid == other.eid
        return self is other

    def __hash__(self):
Rémi Cardona's avatar
Rémi Cardona committed
557
        if isinstance(self.eid, integer_types):
558
559
            return self.eid
        return super(Entity, self).__hash__()
560

561
562
563
    def _cw_update_attr_cache(self, attrcache):
        trdata = self._cw.transaction_data
        uncached_attrs = trdata.get('%s.storage-special-process-attrs' % self.eid, set())
564
        uncached_attrs.update(trdata.get('%s.dont-cache-attrs' % self.eid, set()))
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
        for attr in uncached_attrs:
            attrcache.pop(attr, None)
            self.cw_attr_cache.pop(attr, None)
        self.cw_attr_cache.update(attrcache)

    def _cw_dont_cache_attribute(self, attr, repo_side=False):
        """Called when some attribute has been transformed by a *storage*,
        hence the original value should not be cached **by anyone**.

        For example we have a special "fs_importing" mode in BFSS
        where a file path is given as attribute value and stored as is
        in the data base. Later access to the attribute will provide
        the content of the file at the specified path. We do not want
        the "filepath" value to be cached.

        """
        trdata = self._cw.transaction_data
582
583
584
        trdata.setdefault('%s.dont-cache-attrs' % self.eid, set()).add(attr)
        if repo_side:
            trdata.setdefault('%s.storage-special-process-attrs' % self.eid, set()).add(attr)
585

586
587
588
589
    def __json_encode__(self):
        """custom json dumps hook to dump the entity's eid
        which is not part of dict structure itself
        """
590
        dumpable = self.cw_attr_cache.copy()
591
592
593
        dumpable['eid'] = self.eid
        return dumpable

594
595
596
597
598
    def cw_adapt_to(self, interface):
        """return an adapter the entity to the given interface name.

        return None if it can not be adapted.
        """
599
        cache = self._cw_adapters_cache
600
601
602
603
604
605
606
607
        try:
            return cache[interface]
        except KeyError:
            adapter = self._cw.vreg['adapters'].select_or_none(
                interface, self._cw, entity=self)
            cache[interface] = adapter
            return adapter

608
    def has_eid(self): # XXX cw_has_eid
Adrien Di Mascio's avatar
Adrien Di Mascio committed
609
610
611
612
        """return True if the entity has an attributed eid (False
        meaning that the entity has to be created
        """
        try:
613
            int(self.eid)
Adrien Di Mascio's avatar
Adrien Di Mascio committed
614
615
616
617
            return True
        except (ValueError, TypeError):
            return False

618
    def cw_is_saved(self):
Adrien Di Mascio's avatar
Adrien Di Mascio committed
619
        """during entity creation, there is some time during which the entity
620
621
622
        has an eid attributed though it's not saved (eg during
        'before_add_entity' hooks). You can use this method to ensure the entity
        has an eid *and* is saved in its source.
Adrien Di Mascio's avatar
Adrien Di Mascio committed
623
        """
624
        return self.has_eid() and self._cw_is_saved
625

626
    @deprecated('[3.24] cw_metainformation is deprecated')
Adrien Di Mascio's avatar
Adrien Di Mascio committed
627
    @cached
628
    def cw_metainformation(self):
629
630
631
632
        source = self.cw_source[0].name
        return {'type': self.cw_etype,
                'extid': self.cwuri if source != 'system' else None,
                'source': {'uri': source}}
Adrien Di Mascio's avatar
Adrien Di Mascio committed
633

634
    def cw_check_perm(self, action):
635
        self.e_schema.check_perm(self._cw, action, eid=self.eid)
Adrien Di Mascio's avatar
Adrien Di Mascio committed
636

637
    def cw_has_perm(self, action):
638
        return self.e_schema.has_perm(self._cw, action, eid=self.eid)
639

640
    def view(self, __vid, __registry='views', w=None, initargs=None, **kwargs): # XXX cw_view
Adrien Di Mascio's avatar
Adrien Di Mascio committed
641
        """shortcut to apply a view on this entity"""
642
643
644
645
        if initargs is None:
            initargs = kwargs
        else:
            initargs.update(kwargs)
646
        view = self._cw.vreg[__registry].select(__vid, self._cw, rset=self.cw_rset,
647
                                                row=self.cw_row, col=self.cw_col,
648
                                                **initargs)
649
        return view.render(row=self.cw_row, col=self.cw_col, w=w, **kwargs)
Adrien Di Mascio's avatar
Adrien Di Mascio committed
650

651
    def absolute_url(self, *args, **kwargs): # XXX cw_url
Adrien Di Mascio's avatar
Adrien Di Mascio committed
652
        """return an absolute url to view this entity"""
653
654
655
656
657
658
659
        # use *args since we don't want first argument to be "anonymous" to
        # avoid potential clash with kwargs
        if args:
            assert len(args) == 1, 'only 0 or 1 non-named-argument expected'
            method = args[0]
        else:
            method = None
660
        if method in (None, 'view'):
661
            kwargs['_restpath'] = self.rest_path()
Adrien Di Mascio's avatar
Adrien Di Mascio committed
662
663
        else:
            kwargs['rql'] = 'Any X WHERE X eid %s' % self.eid
664
        return self._cw.build_url(method, **kwargs)
Adrien Di Mascio's avatar
Adrien Di Mascio committed
665

666
    def rest_path(self, *args, **kwargs): # XXX cw_rest_path
Adrien Di Mascio's avatar
Adrien Di Mascio committed
667
        """returns a REST-like (relative) path for this entity"""
668
669
        if args or kwargs:
            warn("[3.24] rest_path doesn't take parameters anymore", DeprecationWarning)
670
        mainattr, needcheck = self.cw_rest_attr_info()
Adrien Di Mascio's avatar
Adrien Di Mascio committed
671
        etype = str(self.e_schema)
672
        path = etype.lower()
673
        fallback = False
674
        if mainattr != 'eid':
675
            value = getattr(self, mainattr)
676
            if not can_use_rest_path(value):
677
                mainattr = 'eid'
678
                path = None
679
680
            elif needcheck:
                # make sure url is not ambiguous
681
682
683
684
685
686
                try:
                    nbresults = self.__unique
                except AttributeError:
                    rql = 'Any COUNT(X) WHERE X is %s, X %s %%(value)s' % (
                        etype, mainattr)
                    nbresults = self.__unique = self._cw.execute(rql, {'value' : value})[0][0]
687
688
                if nbresults != 1: # ambiguity?
                    mainattr = 'eid'
689
                    path = None
Adrien Di Mascio's avatar
Adrien Di Mascio committed
690
        if mainattr == 'eid':
691
            value = self.eid
692
693
694
        if path is None:
            # fallback url: <base-url>/<eid> url is used as cw entities uri,
            # prefer it to <base-url>/<etype>/eid/<eid>
695
696
            return text_type(value)
        return u'%s/%s' % (path, self._cw.url_quote(value))
Adrien Di Mascio's avatar
Adrien Di Mascio committed
697

698
    def cw_attr_metadata(self, attr, metadata):
699
        """return a metadata for an attribute (None if unspecified)"""
700
        value = getattr(self, '%s_%s' % (attr, metadata), None)
701
        if value is None and metadata == 'encoding':
702
            value = self._cw.vreg.property_value('ui.encoding')
703
        return value
Adrien Di Mascio's avatar
Adrien Di Mascio committed
704
705

    def printable_value(self, attr, value=_marker, attrtype=None,
706
                        format='text/html', displaytime=True): # XXX cw_printable_value
Adrien Di Mascio's avatar
Adrien Di Mascio committed
707
708
709
710
711
        """return a displayable value (i.e. unicode string) which may contains
        html tags
        """
        attr = str(attr)
        if value is _marker:
712
            value = getattr(self, attr)
713
        if isinstance(value, string_types):
Adrien Di Mascio's avatar
Adrien Di Mascio committed
714
715
716
717
718
            value = value.strip()
        if value is None or value == '': # don't use "not", 0 is an acceptable value
            return u''
        if attrtype is None:
            attrtype = self.e_schema.destination(attr)
Sylvain Thénault's avatar
Sylvain Thénault committed
719
        props = self.e_schema.rdef(attr)
Adrien Di Mascio's avatar
Adrien Di Mascio committed
720
721
722
        if attrtype == 'String':
            # internalinalized *and* formatted string such as schema
            # description...
Sylvain Thénault's avatar
Sylvain Thénault committed
723
            if props.internationalizable:
724
                value = self._cw._(value)
725
            attrformat = self.cw_attr_metadata(attr, 'format')
Adrien Di Mascio's avatar
Adrien Di Mascio committed
726
            if attrformat:
727
728
                return self._cw_mtc_transform(value, attrformat, format,
                                              self._cw.encoding)
Adrien Di Mascio's avatar
Adrien Di Mascio committed
729
        elif attrtype == 'Bytes':
730
            attrformat = self.cw_attr_metadata(attr, 'format')
Adrien Di Mascio's avatar
Adrien Di Mascio committed
731
            if attrformat:
732
733
734
                encoding = self.cw_attr_metadata(attr, 'encoding')
                return self._cw_mtc_transform(value.getvalue(), attrformat, format,
                                              encoding)
Adrien Di Mascio's avatar
Adrien Di Mascio committed
735
            return u''
736
737
        value = self._cw.printable_value(attrtype, value, props,
                                         displaytime=displaytime)
Adrien Di Mascio's avatar
Adrien Di Mascio committed
738
        if format == 'text/html':
Sylvain Thénault's avatar
Sylvain Thénault committed
739
            value = xml_escape(value)
Adrien Di Mascio's avatar
Adrien Di Mascio committed
740
741
        return value

742
743
    def _cw_mtc_transform(self, data, format, target_format, encoding,
                          _engine=ENGINE):
Adrien Di Mascio's avatar
Adrien Di Mascio committed
744
745
        trdata = TransformData(data, format, encoding, appobject=self)
        data = _engine.convert(trdata, target_format).decode()
746
        if target_format == 'text/html':
747
            data = soup2xhtml(data, self._cw.encoding)
Adrien Di Mascio's avatar
Adrien Di Mascio committed
748
        return data
749

Adrien Di Mascio's avatar
Adrien Di Mascio committed
750
751
    # entity cloning ##########################################################

752
    def copy_relations(self, ceid): # XXX cw_copy_relations
Alexandre Fayolle's avatar
Alexandre Fayolle committed
753
754
755
        """copy relations of the object with the given eid on this
        object (this method is called on the newly created copy, and
        ceid designates the original entity).
Adrien Di Mascio's avatar
Adrien Di Mascio committed
756
757
758
759
760

        By default meta and composite relations are skipped.
        Overrides this if you want another behaviour
        """
        assert self.has_eid()
761
        execute = self._cw.execute
762
763
764
765
        skip_copy_for = {'subject': set(), 'object': set()}
        for rtype in self.skip_copy_for:
            skip_copy_for['subject'].add(rtype)
            warn('[3.14] skip_copy_for on entity classes (%s) is deprecated, '
Sylvain Thénault's avatar
Sylvain Thénault committed
766
                 'use cw_skip_copy_for instead with list of couples (rtype, role)' % self.cw_etype,
767
768
769
770
                 DeprecationWarning)
        for rtype, role in self.cw_skip_copy_for:
            assert role in ('subject', 'object'), role
            skip_copy_for[role].add(rtype)
Adrien Di Mascio's avatar
Adrien Di Mascio committed
771
        for rschema in self.e_schema.subject_relations():
772
773
            if rschema.type in skip_copy_for['subject']:
                continue
774
            if rschema.final or rschema.meta or rschema.rule:
Adrien Di Mascio's avatar
Adrien Di Mascio committed
775
                continue
776
777
            # skip already defined relations
            if getattr(self, rschema.type):
Adrien Di Mascio's avatar
Adrien Di Mascio committed
778
                continue
779
780
            # XXX takefirst=True to remove warning triggered by ambiguous relations
            rdef = self.e_schema.rdef(rschema, takefirst=True)
781
            # skip composite relation
Sylvain Thénault's avatar
Sylvain Thénault committed
782
            if rdef.composite:
783
784
785
                continue
            # skip relation with card in ?1 else we either change the copied
            # object (inlined relation) or inserting some inconsistency
Sylvain Thénault's avatar
Sylvain Thénault committed
786
            if rdef.cardinality[1] in '?1':
787
                continue
Adrien Di Mascio's avatar
Adrien Di Mascio committed
788
            rql = 'SET X %s V WHERE X eid %%(x)s, Y eid %%(y)s, Y %s V' % (
789
                rschema.type, rschema.type)
790
            execute(rql, {'x': self.eid, 'y': ceid})
791
            self.cw_clear_relation_cache(rschema.type, 'subject')
Adrien Di Mascio's avatar
Adrien Di Mascio committed
792
        for rschema in self.e_schema.object_relations():
793
            if rschema.meta or rschema.rule:
794
795
                continue
            # skip already defined relations
Sylvain Thénault's avatar
Sylvain Thénault committed
796
            if self.related(rschema.type, 'object'):
797
                continue
798
799
            if rschema.type in skip_copy_for['object']:
                continue
800
801
            # XXX takefirst=True to remove warning triggered by ambiguous relations
            rdef = self.e_schema.rdef(rschema, 'object', takefirst=True)
802
            # skip composite relation
Sylvain Thénault's avatar
Sylvain Thénault committed
803
            if rdef.composite:
Adrien Di Mascio's avatar
Adrien Di Mascio committed
804
805
806
                continue
            # skip relation with card in ?1 else we either change the copied
            # object (inlined relation) or inserting some inconsistency
Sylvain Thénault's avatar
Sylvain Thénault committed
807
            if rdef.cardinality[0] in '?1':
Adrien Di Mascio's avatar
Adrien Di Mascio committed
808
809
                continue
            rql = 'SET V %s X WHERE X eid %%(x)s, Y eid %%(y)s, V %s Y' % (
810
                rschema.type, rschema.type)
811
            execute(rql, {'x': self.eid, 'y': ceid})
812
            self.cw_clear_relation_cache(rschema.type, 'object')
Adrien Di Mascio's avatar
Adrien Di Mascio committed
813
814
815

    # data fetching methods ###################################################

816
    @cached
817
    def as_rset(self): # XXX .cw_as_rset
Adrien Di Mascio's avatar
Adrien Di Mascio committed
818
819
        """returns a resultset containing `self` information"""
        rset = ResultSet([(self.eid,)], 'Any X WHERE X eid %(x)s',
820
                         {'x': self.eid}, [(self.cw_etype,)])
821
822
        rset.req = self._cw
        return rset
823

824
    def _cw_to_complete_relations(self):
Adrien Di Mascio's avatar
Adrien Di Mascio committed
825
826
        """by default complete final relations to when calling .complete()"""
        for rschema in self.e_schema.subject_relations():
827
            if rschema.final:
Adrien Di Mascio's avatar
Adrien Di Mascio committed
828
                continue
Sylvain Thénault's avatar
Sylvain Thénault committed
829
            targets = rschema.objects(self.e_schema)
Adrien Di Mascio's avatar
Adrien Di Mascio committed
830
            if rschema.inlined:
831
                matching_groups = self._cw.user.matching_groups
832
833
834
                if all(matching_groups(e.get_groups('read')) and
                       rschema.rdef(self.e_schema, e).get_groups('read')
                       for e in targets):
Adrien Di Mascio's avatar
Adrien Di Mascio committed
835
                    yield rschema, 'subject'
836

837
    def _cw_to_complete_attributes(self, skip_bytes=True, skip_pwd=True):
Adrien Di Mascio's avatar
Adrien Di Mascio committed
838
839
840
841
842
843
844
        for rschema, attrschema in self.e_schema.attribute_definitions():
            # skip binary data by default
            if skip_bytes and attrschema.type == 'Bytes':
                continue
            attr = rschema.type
            if attr == 'eid':
                continue
Julien Cristau's avatar
Julien Cristau committed
845
            # password retrieval is blocked at the repository server level
Sylvain Thénault's avatar
Sylvain Thénault committed
846
            rdef = rschema.rdef(self.e_schema, attrschema)
847
            if not self._cw.user.matching_groups(rdef.get_groups('read')) \
848
                   or (attrschema.type == 'Password' and skip_pwd):
849
                self.cw_attr_cache[attr] = None
Adrien Di Mascio's avatar
Adrien Di Mascio committed
850
851
                continue
            yield attr
852

853
    _cw_completed = False
854
    def complete(self, attributes=None, skip_bytes=True, skip_pwd=True): # XXX cw_complete
Adrien Di Mascio's avatar
Adrien Di Mascio committed
855
856
857
858
859
860
861
862
        """complete this entity by adding missing attributes (i.e. query the
        repository to fill the entity)

        :type skip_bytes: bool
        :param skip_bytes:
          if true, attribute of type Bytes won't be considered
        """
        assert self.has_eid()
863
864
865
866
        if self._cw_completed:
            return
        if attributes is None:
            self._cw_completed = True
Adrien Di Mascio's avatar
Adrien Di Mascio committed
867
        varmaker = rqlvar_maker()
868
        V = next(varmaker)
Adrien Di Mascio's avatar
Adrien Di Mascio committed
869
870
        rql = ['WHERE %s eid %%(x)s' % V]
        selected = []
871
        for attr in (attributes or self._cw_to_complete_attributes(skip_bytes, skip_pwd)):
Adrien Di Mascio's avatar
Adrien Di Mascio committed
872
            # if attribute already in entity, nothing to do
873
            if attr in self.cw_attr_cache:
Adrien Di Mascio's avatar
Adrien Di Mascio committed
874
875
                continue
            # case where attribute must be completed, but is not yet in entity
876
            var = next(varmaker)
Adrien Di Mascio's avatar
Adrien Di Mascio committed
877
878
            rql.append('%s %s %s' % (V, attr, var))
            selected.append((attr, var))
879
        # +1 since this doesn't include the main variable
Adrien Di Mascio's avatar
Adrien Di Mascio committed
880
        lastattr = len(selected) + 1
881
        if attributes is None:
Adrien Di Mascio's avatar
Adrien Di Mascio committed
882
            # fetch additional relations (restricted to 0..1 relations)
883
            for rschema, role in self._cw_to_complete_relations():
Adrien Di Mascio's avatar
Adrien Di Mascio committed
884
                rtype = rschema.type
885
                if self.cw_relation_cached(rtype, role):
Adrien Di Mascio's avatar
Adrien Di Mascio committed
886
                    continue
887
888
889
890
891
892
                # at this point we suppose that:
                # * this is a inlined relation
                # * entity (self) is the subject
                # * user has read perm on the relation and on the target entity
                assert rschema.inlined
                assert role == 'subject'
893
                var = next(varmaker)
894
895
896
                # keep outer join anyway, we don't want .complete to crash on
                # missing mandatory relation (see #1058267)
                rql.append('%s %s %s?' % (V, rtype, var))
Adrien Di Mascio's avatar
Adrien Di Mascio committed
897
898
899
900
901
902
                selected.append(((rtype, role), var))
        if selected:
            # select V, we need it as the left most selected variable
            # if some outer join are included to fetch inlined relations
            rql = 'Any %s,%s %s' % (V, ','.join(var for attr, var in selected),
                                    ','.join(rql))
903
904
905
906
907
            try:
                rset = self._cw.execute(rql, {'x': self.eid}, build_descr=False)[0]
            except IndexError:
                raise Exception('unable to fetch attributes for entity with eid %s'
                                % self.eid)
Adrien Di Mascio's avatar
Adrien Di Mascio committed
908
            # handle attributes
909
            for i in range(1, lastattr):
910
                self.cw_attr_cache[str(selected[i-1][0])] = rset[i]
Adrien Di Mascio's avatar
Adrien Di Mascio committed
911
            # handle relations
912
            for i in range(lastattr, len(rset)):
913
                rtype, role = selected[i-1][0]
Adrien Di Mascio's avatar
Adrien Di Mascio committed
914
915
916
                value = rset[i]
                if value is None:
                    rrset = ResultSet([], rql, {'x': self.eid})
917
                    rrset.req = self._cw
Adrien Di Mascio's avatar
Adrien Di Mascio committed
918
                else:
919
                    rrset = self._cw.eid_rset(value)
920
                self.cw_set_relation_cache(rtype, role, rrset)
921

922
    def cw_attr_value(self, name):
Adrien Di Mascio's avatar
Adrien Di Mascio committed
923
924
925
926
927
928
929
        """get value for the attribute relation <name>, query the repository
        to get the value if necessary.

        :type name: str
        :param name: name of the attribute to get
        """
        try:
930
            return self.cw_attr_cache[name]
Adrien Di Mascio's avatar
Adrien Di Mascio committed
931
        except KeyError:
932
            if not self.cw_is_saved():
Adrien Di Mascio's avatar
Adrien Di Mascio committed
933
934
935
                return None
            rql = "Any A WHERE X eid %%(x)s, X %s A" % name
            try:
936
                rset = self._cw.execute(rql, {'x': self.eid})
Adrien Di Mascio's avatar
Adrien Di Mascio committed
937
            except Unauthorized:
938
                self.cw_attr_cache[name] = value = None
Adrien Di Mascio's avatar
Adrien Di Mascio committed
939
940
941
            else:
                assert rset.rowcount <= 1, (self, rql, rset.rowcount)
                try:
942
                    self.cw_attr_cache[name] = value = rset.rows[0][0]
Adrien Di Mascio's avatar
Adrien Di Mascio committed
943
944
945
946
947
                except IndexError:
                    # probably a multisource error
                    self.critical("can't get value for attribute %s of entity with eid %s",
                                  name, self.eid)
                    if self.e_schema.destination(name) == 'String':
948
                        self.cw_attr_cache[name] = value = self._cw._('unaccessible')
Adrien Di Mascio's avatar
Adrien Di Mascio committed
949
                    else:
950
951
                        self.cw_attr_cache[name] = value = None
            return value
Adrien Di Mascio's avatar
Adrien Di Mascio committed
952

953
    def related(self, rtype, role='subject', limit=None, entities=False, # XXX .cw_related
954
                safe=False, targettypes=None):
Adrien Di Mascio's avatar
Adrien Di Mascio committed
955
        """returns a resultset of related entities
956

957
958
959
960
961
962
963
964
965
966
967
        :param rtype:
          the name of the relation, aka relation type
        :param role:
          the role played by 'self' in the relation ('subject' or 'object')
        :param limit:
          resultset's maximum size
        :param entities:
          if True, the entites are returned; if False, a result set is returned
        :param safe:
          if True, an empty rset/list of entities will be returned in case of
          :exc:`Unauthorized`, else (the default), the exception is propagated
968
969
        :param targettypes:
          a tuple of target entity types to restrict the query
Adrien Di Mascio's avatar
Adrien Di Mascio committed
970
        """
971
        rtype = str(rtype)
972
973
974
        # Caching restricted/limited results is best avoided.
        cacheable = limit is None and targettypes is None
        if cacheable:
975
976
977
            cache_key = '%s_%s' % (rtype, role)
            if cache_key in self._cw_related_cache:
                return self._cw_related_cache[cache_key][entities]
978
979
980
        if not self.has_eid():
            if entities:
                return []
981
            return self._cw.empty_rset()
982
        rql = self.cw_related_rql(rtype, role, limit=limit, targettypes=targettypes)
983
984
985
986
987
988
        try:
            rset = self._cw.execute(rql, {'x': self.eid})
        except Unauthorized:
            if not safe:
                raise
            rset = self._cw.empty_rset()
989
        if entities:
990
            if cacheable:
991
                self.cw_set_relation_cache(rtype, role, rset)
992
                return self.related(rtype, role, entities=entities)
993
994
995
            return list(