Exemplo n.º 1
0
    def possible_relations(self, select, rql_var, include_meta=False):
        """returns a list of couple (rtype, dest_var) for each possible
        relations with `rql_var` as subject.

        ``dest_var`` will be picked among availabel variables if types match,
        otherwise a new one will be created.
        """
        schema = self._cw.vreg.schema
        relations = set()
        untyped_dest_var = next(rqlvar_maker(defined=select.defined_vars))
        # for each solution
        # 1. find each possible relation
        # 2. for each relation:
        #    2.1. if the relation is meta, skip it
        #    2.2. for each possible destination type, pick up possible
        #         variables for this type or use a new one
        for sol in select.solutions:
            etype = sol[rql_var]
            sol_by_types = {}
            for varname, var_etype in sol.items():
                # don't push subject var to avoid "X relation X" suggestion
                if varname != rql_var:
                    sol_by_types.setdefault(var_etype, []).append(varname)
            for rschema in schema[etype].subject_relations():
                if include_meta or not rschema.meta:
                    for dest in rschema.objects(etype):
                        for varname in sol_by_types.get(dest.type, (untyped_dest_var,)):
                            suggestion = (rschema.type, varname)
                            if suggestion not in relations:
                                relations.add(suggestion)
        return sorted(relations)
Exemplo n.º 2
0
    def find_users(self, fetch_attrs, **query_attrs):
        """yield user attributes for cwusers matching the given query_attrs
        (the result set cannot survive this method call)

        This can be used by low-privileges account (anonymous comes to
        mind).

        `fetch_attrs`: tuple of attributes to be fetched
        `query_attrs`: dict of attr/values to restrict the query
        """
        assert query_attrs
        if not hasattr(self, '_cwuser_attrs'):
            cwuser = self.schema['CWUser']
            self._cwuser_attrs = set(
                str(rschema)
                for rschema, _eschema in cwuser.attribute_definitions()
                if not rschema.meta)
        cwuserattrs = self._cwuser_attrs
        for k in chain(fetch_attrs, query_attrs):
            if k not in cwuserattrs:
                raise Exception('bad input for find_user')
        with self.internal_cnx() as cnx:
            varmaker = rqlvar_maker()
            vars = [(attr, next(varmaker)) for attr in fetch_attrs]
            rql = 'Any %s WHERE X is CWUser, ' % ','.join(var[1]
                                                          for var in vars)
            rql += ','.join('X %s %s' % (var[0], var[1]) for var in vars) + ','
            rset = cnx.execute(
                rql + ','.join('X %s %%(%s)s' % (attr, attr)
                               for attr in query_attrs), query_attrs)
            return rset.rows
Exemplo n.º 3
0
 def allocate_varname(self):
     """return an yet undefined variable name"""
     if self._varmaker is None:
         self._varmaker = rqlvar_maker(
             defined=self.defined_vars,
             # XXX only on Select node
             aliases=getattr(self, 'aliases', None))
     return next(self._varmaker)
Exemplo n.º 4
0
 def test_rqlvar_maker_dontstop(self):
     varlist = utils.rqlvar_maker()
     self.assertEqual(next(varlist), 'A')
     self.assertEqual(next(varlist), 'B')
     for i in range(24):
         next(varlist)
     self.assertEqual(next(varlist), 'AA')
     self.assertEqual(next(varlist), 'AB')
Exemplo n.º 5
0
 def update_query(self, eid):
     assert not self.canceled
     varmaker = rqlvar_maker()
     var = next(varmaker)
     while var in self.kwargs:
         var = next(varmaker)
     rql = 'SET %s WHERE X eid %%(%s)s' % (','.join(self.edited), var)
     if self.restrictions:
         rql += ', %s' % ','.join(self.restrictions)
     self.kwargs[var] = eid
     return rql
Exemplo n.º 6
0
    def find(self, etype, **kwargs):
        """find entities of the given type and attribute values.

        :returns: A :class:`ResultSet`

        >>> users = find('CWGroup', name=u"users").one()
        >>> groups = find('CWGroup').entities()
        """
        parts = ['Any X WHERE X is {0}'.format(etype)]
        varmaker = rqlvar_maker(defined='X')
        eschema = self.vreg.schema.eschema(etype)
        for attr, value in kwargs.items():
            if isinstance(value, list) or isinstance(value, tuple):
                raise NotImplementedError(
                    '{0}: list of values are not supported'.format(attr))
            if hasattr(value, 'eid'):
                kwargs[attr] = value.eid
            if attr.startswith('reverse_'):
                attr = attr[8:]
                if attr not in eschema.objrels:
                    raise KeyError('{0} not in {1} object relations'.format(
                        attr, eschema))
                parts.append(
                    '{var} {attr} X, {var} eid %(reverse_{attr})s'.format(
                        var=next(varmaker), attr=attr))
            else:
                rel = eschema.subjrels.get(attr)
                if rel is None:
                    raise KeyError('{0} not in {1} subject relations'.format(
                        attr, eschema))
                if rel.final:
                    parts.append('X {attr} %({attr})s'.format(attr=attr))
                else:
                    parts.append('X {attr} {var}, {var} eid %({attr})s'.format(
                        attr=attr, var=next(varmaker)))

        rql = ', '.join(parts)

        return self.execute(rql, kwargs)
Exemplo n.º 7
0
 def set_varmaker(self):
     varmaker = self.get_page_data('rql_varmaker')
     if varmaker is None:
         varmaker = rqlvar_maker()
     self.set_page_data('rql_varmaker', varmaker)
     return varmaker
Exemplo n.º 8
0
 def test_rqlvar_maker(self):
     varlist = list(utils.rqlvar_maker(27))
     self.assertEqual(varlist, list('ABCDEFGHIJKLMNOPQRSTUVWXYZ') + ['AA'])
     varlist = list(utils.rqlvar_maker(27 * 26 + 1))
     self.assertEqual(varlist[-2], 'ZZ')
     self.assertEqual(varlist[-1], 'AAA')