backport stable branch
authorSylvain Thénault <sylvain.thenault@logilab.fr>
Wed, 21 Oct 2009 17:32:20 +0200
changeset 3777 3ef8cdb5fb1c
parent 3739 817e96eeac5c (current diff)
parent 3776 d98f2c390916 (diff)
child 3810 5b75fd66c80e
backport stable branch
__pkginfo__.py
devtools/testlib.py
doc/book/en/toc.rst
entities/wfobjs.py
entity.py
hooks/syncschema.py
hooks/workflow.py
rset.py
selectors.py
server/repository.py
server/test/unittest_repository.py
server/test/unittest_rql2sql.py
test/unittest_entity.py
web/__init__.py
web/component.py
web/test/unittest_form.py
web/test/unittest_views_basecontrollers.py
web/test/unittest_views_baseviews.py
web/test/unittest_views_editforms.py
web/views/basecontrollers.py
web/views/editforms.py
web/views/navigation.py
web/views/schema.py
--- a/.hgtags	Mon Oct 19 20:22:01 2009 +0200
+++ b/.hgtags	Wed Oct 21 17:32:20 2009 +0200
@@ -80,3 +80,5 @@
 2e22b975f9c23aebfe3e0a16a798c3fe81fa2a82 cubicweb-debian-version-3.5.3-1
 312349b3712e0a3e32247e03fdc7408e17bd19de cubicweb-version-3.5.4
 37d025b2aa7735dae4a861059014c560b45b19e6 cubicweb-debian-version-3.5.4-1
+1eca47d59fd932fe23f643ca239cf2408e5b1856 cubicweb-version-3.5.5
+aad818d9d9b6fdb2ffea56c0a9af718c0b69899d cubicweb-debian-version-3.5.5-1
--- a/__pkginfo__.py	Mon Oct 19 20:22:01 2009 +0200
+++ b/__pkginfo__.py	Wed Oct 21 17:32:20 2009 +0200
@@ -7,7 +7,7 @@
 distname = "cubicweb"
 modname = "cubicweb"
 
-numversion = (3, 5, 4)
+numversion = (3, 5, 5)
 version = '.'.join(str(num) for num in numversion)
 
 license = 'LGPL v2'
--- a/debian/changelog	Mon Oct 19 20:22:01 2009 +0200
+++ b/debian/changelog	Wed Oct 21 17:32:20 2009 +0200
@@ -1,3 +1,9 @@
+cubicweb (3.5.5-1) unstable; urgency=low
+
+  * new upstream release
+
+ -- Sylvain Thénault <sylvain.thenault@logilab.fr>  Wed, 21 Oct 2009 10:38:55 +0200
+
 cubicweb (3.5.4-1) unstable; urgency=low
 
   * new upstream release
--- a/debian/control	Mon Oct 19 20:22:01 2009 +0200
+++ b/debian/control	Wed Oct 21 17:32:20 2009 +0200
@@ -76,7 +76,7 @@
 Package: cubicweb-common
 Architecture: all
 XB-Python-Version: ${python:Versions}
-Depends: ${python:Depends}, graphviz, gettext, python-logilab-mtconverter (>= 0.6.0), python-logilab-common (>= 0.44.0), python-yams (>= 0.24.0), python-rql (>= 0.22.3), python-lxml
+Depends: ${python:Depends}, graphviz, gettext, python-logilab-mtconverter (>= 0.6.0), python-logilab-common (>= 0.44.0), python-yams (>= 0.25.0), python-rql (>= 0.22.3), python-lxml
 Recommends: python-simpletal (>= 4.0)
 Conflicts: cubicweb-core
 Replaces: cubicweb-core
--- a/devtools/fill.py	Mon Oct 19 20:22:01 2009 +0200
+++ b/devtools/fill.py	Wed Oct 21 17:32:20 2009 +0200
@@ -308,13 +308,16 @@
 
 
 
-def select(constraints, cursor, selectvar='O'):
+def select(constraints, cursor, selectvar='O', objtype=None):
     """returns list of eids matching <constraints>
 
     <selectvar> should be either 'O' or 'S' to match schema definitions
     """
     try:
-        rset = cursor.execute('Any %s WHERE %s' % (selectvar, constraints))
+        rql = 'Any %s WHERE %s' % (selectvar, constraints)
+        if objtype:
+            rql += ', %s is %s' % (selectvar, objtype)
+        rset = cursor.execute(rql)
     except:
         print "could restrict eid_list with given constraints (%r)" % constraints
         return []
@@ -335,6 +338,14 @@
     gen = RelationsQueriesGenerator(schema, cursor, existingrels)
     return gen.compute_queries(edict, ignored_relations)
 
+def composite_relation(rschema):
+    for obj in rschema.objects():
+        if obj.objrproperty(rschema, 'composite') == 'subject':
+            return True
+    for obj in rschema.subjects():
+        if obj.subjrproperty(rschema, 'composite') == 'object':
+            return True
+    return False
 
 class RelationsQueriesGenerator(object):
     rql_tmpl = 'SET S %s O WHERE S eid %%(subjeid)s, O eid %%(objeid)s'
@@ -346,8 +357,9 @@
     def compute_queries(self, edict, ignored_relations):
         queries = []
         #   1/ skip final relations and explictly ignored relations
-        rels = [rschema for rschema in self.schema.relations()
-                if not (rschema.final or rschema in ignored_relations)]
+        rels = sorted([rschema for rschema in self.schema.relations()
+                       if not (rschema.final or rschema in ignored_relations)],
+                      key=lambda x:not composite_relation(x))
         # for each relation
         #   2/ take each possible couple (subj, obj)
         #   3/ analyze cardinality of relation
@@ -366,15 +378,16 @@
                     continue
                 subjcard, objcard = rschema.rproperty(subj, obj, 'cardinality')
                 # process mandatory relations first
-                if subjcard in '1+' or objcard in '1+':
-                    queries += self.make_relation_queries(sedict, oedict,
-                                                          rschema, subj, obj)
+                if subjcard in '1+' or objcard in '1+' or composite_relation(rschema):
+                    for query, args in self.make_relation_queries(sedict, oedict,
+                                                          rschema, subj, obj):
+                        yield query, args
                 else:
                     delayed.append( (subj, obj) )
             for subj, obj in delayed:
-                queries += self.make_relation_queries(sedict, oedict, rschema,
-                                                      subj, obj)
-        return queries
+                for query, args in self.make_relation_queries(sedict, oedict, rschema,
+                                                              subj, obj):
+                    yield query, args
 
     def qargs(self, subjeids, objeids, subjcard, objcard, subjeid, objeid):
         if subjcard in '?1':
@@ -399,10 +412,9 @@
             # restrict object eids if possible
             # XXX the attempt to restrict below in completely wrong
             # disabling it for now
-            objeids = select(restrictions, self.cursor)
+            objeids = select(restrictions, self.cursor, objtype=obj)
         else:
             objeids = oedict.get(obj, frozenset())
-##         objeids = oedict.get(obj, frozenset())
         if subjcard in '?1' or objcard in '?1':
             for subjeid, objeid in used:
                 if subjcard in '?1' and subjeid in subjeids:
@@ -461,8 +473,9 @@
 
 def check_card_satisfied(card, remaining, subj, rschema, obj):
     if card in '1+' and remaining:
-        raise Exception("can't satisfy cardinality %s for relation %s %s %s"
-                        % (card, subj, rschema, obj))
+        raise Exception("can't satisfy cardinality %s for relation %s %s %s" %
+                        (card, subj, rschema, obj))
+
 
 def choose_eid(values, avoid):
     values = tuple(values)
--- a/devtools/test/unittest_dbfill.py	Mon Oct 19 20:22:01 2009 +0200
+++ b/devtools/test/unittest_dbfill.py	Wed Oct 21 17:32:20 2009 +0200
@@ -46,9 +46,9 @@
         config = ApptestConfiguration('data')
         config.bootstrap_cubes()
         schema = config.load_schema()
-        e_schema = schema.entity_schema('Person')
+        e_schema = schema.eschema('Person')
         self.person_valgen = ValueGenerator(e_schema, self._choice_func)
-        e_schema = schema.entity_schema('Bug')
+        e_schema = schema.eschema('Bug')
         self.bug_valgen = MyValueGenerator(e_schema)
         self.config = config
 
--- a/devtools/testlib.py	Mon Oct 19 20:22:01 2009 +0200
+++ b/devtools/testlib.py	Wed Oct 21 17:32:20 2009 +0200
@@ -837,7 +837,7 @@
             if k.endswith('visible') and not v['default']:
                 propdefs[k]['default'] = True
         for view in self.list_views_for(rset):
-            backup_rset = rset._prepare_copy(rset.rows, rset.description)
+            backup_rset = rset.copy(rset.rows, rset.description)
             yield InnerTest(self._testname(rset, view.__regid__, 'view'),
                             self.view, view.__regid__, rset,
                             rset.req.reset_headers(), 'main-template')
--- a/doc/book/en/admin/index.rst	Mon Oct 19 20:22:01 2009 +0200
+++ b/doc/book/en/admin/index.rst	Wed Oct 21 17:32:20 2009 +0200
@@ -11,6 +11,7 @@
 
 .. toctree::
    :maxdepth: 1
+   :numbered:
 
    setup
    create-instance
@@ -20,8 +21,6 @@
    ldap
    gae
 
-
-
 RQL logs
 --------
 
@@ -33,3 +32,4 @@
 
   # web instance query log file
   query-log-file=/tmp/rql-myapp.log
+
--- a/doc/book/en/admin/instance-config.rst	Mon Oct 19 20:22:01 2009 +0200
+++ b/doc/book/en/admin/instance-config.rst	Wed Oct 21 17:32:20 2009 +0200
@@ -65,7 +65,7 @@
      https-url = `https://localhost/demo`
 
 Setting up the web
---------------------------------
+------------------
 :`web.embed-allowed`:
     regular expression matching sites which could be "embedded" in
     the site (controllers 'embed')
--- a/doc/book/en/admin/setup.rst	Mon Oct 19 20:22:01 2009 +0200
+++ b/doc/book/en/admin/setup.rst	Wed Oct 21 17:32:20 2009 +0200
@@ -2,7 +2,6 @@
 
 .. _SetUpEnv:
 
-===================================================
 Installation and set-up of a *CubicWeb* environment
 ===================================================
 
--- a/doc/book/en/annexes/index.rst	Mon Oct 19 20:22:01 2009 +0200
+++ b/doc/book/en/annexes/index.rst	Wed Oct 21 17:32:20 2009 +0200
@@ -10,6 +10,7 @@
 
 .. toctree::
    :maxdepth: 1
+   :numbered:
 
    faq
    cookbook
--- a/doc/book/en/development/index.rst	Mon Oct 19 20:22:01 2009 +0200
+++ b/doc/book/en/development/index.rst	Wed Oct 21 17:32:20 2009 +0200
@@ -8,6 +8,7 @@
 
 .. toctree::
    :maxdepth: 2
+   :numbered:
 
    cubes/index
    datamodel/index
--- a/doc/book/en/intro/history.rst	Mon Oct 19 20:22:01 2009 +0200
+++ b/doc/book/en/intro/history.rst	Wed Oct 21 17:32:20 2009 +0200
@@ -1,7 +1,7 @@
 .. -*- coding: utf-8 -*-
 
 A little history...
-======================
+===================
 
 *CubicWeb* is a semantic web application framework that Logilab_ started
 developing in 2001 as an offspring of its Narval_ research project. *CubicWeb*
--- a/doc/book/en/intro/index.rst	Mon Oct 19 20:22:01 2009 +0200
+++ b/doc/book/en/intro/index.rst	Wed Oct 21 17:32:20 2009 +0200
@@ -13,6 +13,7 @@
 
 .. toctree::
    :maxdepth: 2
+   :numbered:
 
    book-map
    history
--- a/doc/book/en/toc.rst	Mon Oct 19 20:22:01 2009 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,25 +0,0 @@
-.. -*- coding: utf-8 -*-
-
-.. _TOC:
-
-Table of contents
-=================
-
-
-.. toctree::
-   :numbered:
-
-   intro/concepts/index
-   development/cubes/index
-   development/datamodel/index
-   development/entityclasses/index
-   development/devcore/index
-   development/devweb/index
-   development/devrepo/index
-   development/testing/index
-   development/migration/index
-   development/webstdlib/index
-   admin/index
-   annexes/rql/index
-   annexes/index
-
--- a/entities/wfobjs.py	Mon Oct 19 20:22:01 2009 +0200
+++ b/entities/wfobjs.py	Wed Oct 21 17:32:20 2009 +0200
@@ -412,7 +412,10 @@
 
     def latest_trinfo(self):
         """return the latest transition information for this entity"""
-        return self.reverse_wf_info_for[-1]
+        try:
+            return self.reverse_wf_info_for[-1]
+        except IndexError:
+            return None
 
     @cached
     def cwetype_workflow(self):
--- a/entity.py	Mon Oct 19 20:22:01 2009 +0200
+++ b/entity.py	Wed Oct 21 17:32:20 2009 +0200
@@ -782,6 +782,8 @@
                 restr = 'Y %s X' % attr[len('reverse_'):]
             else:
                 restr = 'X %s Y' % attr
+            if not isinstance(values, (tuple, list, set, frozenset)):
+                values = (values,)
             execute('SET %s WHERE X eid %%(x)s, Y eid IN (%s)' % (
                 restr, ','.join(str(r.eid) for r in values)),
                     {'x': self.eid}, 'x')
--- a/hooks/syncschema.py	Mon Oct 19 20:22:01 2009 +0200
+++ b/hooks/syncschema.py	Wed Oct 21 17:32:20 2009 +0200
@@ -16,6 +16,8 @@
 from yams.buildobjs import EntityType, RelationType, RelationDefinition
 from yams.schema2sql import eschema2sql, rschema2sql, type_from_constraints
 
+from logilab.common.decorators import clear_cache
+
 from cubicweb import ValidationError, RepositoryError
 from cubicweb.selectors import entity_implements
 from cubicweb.schema import META_RTYPES, VIRTUAL_RTYPES, CONSTRAINTS
@@ -144,11 +146,19 @@
     def __init__(self, session):
         hook.SingleLastOperation.__init__(self, session)
 
+    def precommit_event(self):
+        for eschema in self.repo.schema.entities():
+            if not eschema.final:
+                clear_cache(eschema, 'ordered_relations')
+
     def commit_event(self):
         rebuildinfered = self.session.data.get('rebuild-infered', True)
         repo = self.session.repo
         repo.set_schema(repo.schema, rebuildinfered=rebuildinfered)
 
+    def rollback_event(self):
+        self.precommit_event()
+
 
 class MemSchemaOperation(hook.Operation):
     """base class for schema operations"""
--- a/hooks/workflow.py	Mon Oct 19 20:22:01 2009 +0200
+++ b/hooks/workflow.py	Wed Oct 21 17:32:20 2009 +0200
@@ -212,7 +212,7 @@
                 msg = session._('mandatory relation')
                 raise ValidationError(entity.eid, {'by_transition': msg})
             deststate = wf.state_by_eid(deststateeid)
-            if not cowpowers and deststate is None:
+            if deststate is None:
                 msg = session._("state doesn't belong to entity's workflow")
                 raise ValidationError(entity.eid, {'to_state': msg})
         else:
--- a/i18n/en.po	Mon Oct 19 20:22:01 2009 +0200
+++ b/i18n/en.po	Wed Oct 21 17:32:20 2009 +0200
@@ -1954,15 +1954,17 @@
 msgid "description_format"
 msgstr "format"
 
-msgid "destination state"
-msgstr ""
-
 msgid "destination state for this transition"
 msgstr ""
 
 msgid "destination state of a transition"
 msgstr ""
 
+msgid ""
+"destination state. No destination state means that transition should go back "
+"to the state from which we've entered the subworkflow."
+msgstr ""
+
 msgid "destination_state"
 msgstr "destination state"
 
--- a/i18n/es.po	Mon Oct 19 20:22:01 2009 +0200
+++ b/i18n/es.po	Wed Oct 21 17:32:20 2009 +0200
@@ -2015,15 +2015,17 @@
 msgid "description_format"
 msgstr ""
 
-msgid "destination state"
-msgstr ""
-
 msgid "destination state for this transition"
 msgstr "Estado destino para esta transición"
 
 msgid "destination state of a transition"
 msgstr "Estado destino de una transición"
 
+msgid ""
+"destination state. No destination state means that transition should go back "
+"to the state from which we've entered the subworkflow."
+msgstr ""
+
 msgid "destination_state"
 msgstr "Estado destino"
 
--- a/i18n/fr.po	Mon Oct 19 20:22:01 2009 +0200
+++ b/i18n/fr.po	Wed Oct 21 17:32:20 2009 +0200
@@ -2027,15 +2027,19 @@
 msgid "description_format"
 msgstr "format"
 
-msgid "destination state"
-msgstr "état de destination"
-
 msgid "destination state for this transition"
 msgstr "états accessibles par cette transition"
 
 msgid "destination state of a transition"
 msgstr "état d'arrivée d'une transition"
 
+msgid ""
+"destination state. No destination state means that transition should go back "
+"to the state from which we've entered the subworkflow."
+msgstr ""
+"état de destination de la transition. Si aucun état de destination n'est spécifié, la transition "
+"ira vers l'état depuis lequel l'entité est entrée dans le sous-workflow."
+
 msgid "destination_state"
 msgstr "état de destination"
 
@@ -4022,6 +4026,9 @@
 msgid "you should probably delete that property"
 msgstr "vous devriez probablement supprimer cette propriété"
 
+#~ msgid "destination state"
+#~ msgstr "état de destination"
+
 #~ msgctxt "inlined:CWRelation:from_entity:subject"
 #~ msgid "remove this CWEType"
 #~ msgstr "supprimer ce type d'entité"
--- a/rset.py	Mon Oct 19 20:22:01 2009 +0200
+++ b/rset.py	Wed Oct 21 17:32:20 2009 +0200
@@ -117,11 +117,10 @@
                          self.description +rset.description)
         return self.req.decorate_rset(rset)
 
-    def copy(self):
-        rset = ResultSet(self.rows[:], self.rql, self.args, self.description[:])
-        return self.req.decorate_rset(rset)
-
-    def _prepare_copy(self, rows, descr):
+    def copy(self, rows=None, descr=None):
+        if rows is None:
+            rows = self.rows[:]
+            descr = self.description[:]
         rset = ResultSet(rows, self.rql, self.args, descr)
         return self.req.decorate_rset(rset)
 
@@ -140,7 +139,7 @@
         :rtype: `ResultSet`
         """
         rows, descr = [], []
-        rset = self._prepare_copy(rows, descr)
+        rset = self.copy(rows, descr)
         for row, desc in zip(self.rows, self.description):
             nrow, ndesc = transformcb(row, desc)
             if ndesc: # transformcb returns None for ndesc to skip that row
@@ -163,7 +162,7 @@
         :rtype: `ResultSet`
         """
         rows, descr = [], []
-        rset = self._prepare_copy(rows, descr)
+        rset = self.copy(rows, descr)
         for i in xrange(len(self)):
             if not filtercb(self.get_entity(i, col)):
                 continue
@@ -190,7 +189,7 @@
         :rtype: `ResultSet`
         """
         rows, descr = [], []
-        rset = self._prepare_copy(rows, descr)
+        rset = self.copy(rows, descr)
         if col >= 0:
             entities = sorted(enumerate(self.entities(col)),
                               key=lambda (i, e): keyfunc(e), reverse=reverse)
@@ -237,7 +236,7 @@
 
             if key not in mapping:
                 rows, descr = [], []
-                rset = self._prepare_copy(rows, descr)
+                rset = self.copy(rows, descr)
                 mapping[key] = rset
                 result.append(rset)
             else:
@@ -332,7 +331,7 @@
                     else:
                         self.req.drop_entity_cache(entity.eid)
         else:
-            rset = self._prepare_copy(rows, descr)
+            rset = self.copy(rows, descr)
             if not offset:
                 # can copy built entity caches
                 copy_cache(rset, 'get_entity', self)
@@ -558,6 +557,9 @@
         # UNION query, find the subquery from which this entity has been found
         select = rqlst.locate_subquery(locate_query_col, etype, self.args)[0]
         col = rqlst.subquery_selection_index(select, col)
+        if col is None:
+            # XXX unexpected, should fix subquery_selection_index ?
+            return None, None
         try:
             myvar = select.selection[col].variable
         except AttributeError:
--- a/schemaviewer.py	Mon Oct 19 20:22:01 2009 +0200
+++ b/schemaviewer.py	Wed Oct 21 17:32:20 2009 +0200
@@ -31,9 +31,11 @@
         data = [self.req._('access type'), self.req._('groups')]
         for access_type in access_types:
             data.append(self.req._(access_type))
-            acls = [self.req._(group) for group in schema.get_groups(access_type)]
-            acls += (rqlexp.expression for rqlexp in schema.get_rqlexprs(access_type))
-            data.append(', '.join(acls))
+            acls = [Link(self.req.build_url('cwgroup/%s' % group), self.req._(group))
+                    for group in schema.get_groups(access_type)]
+            acls += (Text(rqlexp.expression) for rqlexp in schema.get_rqlexprs(access_type))
+            acls = [n for _n in acls for n in (_n, Text(', '))][:-1]
+            data.append(Span(children=acls))
         return Section(children=(Table(cols=2, cheaders=1, rheaders=1, children=data),),
                        klass='acl')
 
@@ -107,7 +109,7 @@
         layout.append(Link(etype,'&#160;' , id=etype)) # anchor
         title = Link(self.eschema_link_url(eschema), etype)
         boxchild = [Section(children=(title, ' (%s)'% eschema.display_name(self.req)), klass='title')]
-        table = Table(cols=4, rheaders=1,
+        table = Table(cols=4, rheaders=1, klass='listing',
                       children=self._entity_attributes_data(eschema))
         boxchild.append(Section(children=(table,), klass='body'))
         data = []
@@ -158,18 +160,21 @@
     def visit_relationschema(self, rschema, title=True):
         """get a layout for a relation schema"""
         _ = self.req._
-        title = Link(self.rschema_link_url(rschema), rschema.type)
-        stereotypes = []
-        if rschema.meta:
-            stereotypes.append('meta')
-        if rschema.symetric:
-            stereotypes.append('symetric')
-        if rschema.inlined:
-            stereotypes.append('inlined')
-        title = Section(children=(title, ' (%s)'%rschema.display_name(self.req)), klass='title')
-        if stereotypes:
-            title.append(self.stereotype(','.join(stereotypes)))
-        layout = Section(children=(title,), klass='schema')
+        if title:
+            title = Link(self.rschema_link_url(rschema), rschema.type)
+            stereotypes = []
+            if rschema.meta:
+                stereotypes.append('meta')
+            if rschema.symetric:
+                stereotypes.append('symetric')
+            if rschema.inlined:
+                stereotypes.append('inlined')
+            title = Section(children=(title, ' (%s)'%rschema.display_name(self.req)), klass='title')
+            if stereotypes:
+                title.append(self.stereotype(','.join(stereotypes)))
+            layout = Section(children=(title,), klass='schema')
+        else:
+            layout = Section(klass='schema')
         data = [_('from'), _('to')]
         schema = rschema.schema
         rschema_objects = rschema.objects()
@@ -202,7 +207,7 @@
                     else:
                         val = str(val)
                     data.append(Text(val))
-        table = Table(cols=cols, rheaders=1, children=data)
+        table = Table(cols=cols, rheaders=1, children=data, klass='listing')
         layout.append(Section(children=(table,), klass='relationDefinition'))
         if not self.req.cnx.anonymous_connection:
             layout.append(self.format_acls(rschema, ('read', 'add', 'delete')))
--- a/server/sources/rql2sql.py	Mon Oct 19 20:22:01 2009 +0200
+++ b/server/sources/rql2sql.py	Wed Oct 21 17:32:20 2009 +0200
@@ -107,8 +107,8 @@
                 if rel.optional in ('right', 'both'):
                     var.stinfo['optrelations'].add(newrel)
         # extract subquery solutions
-        solutions = [sol.copy() for sol in solutions]
-        cleanup_solutions(newselect, solutions)
+        mysolutions = [sol.copy() for sol in solutions]
+        cleanup_solutions(newselect, mysolutions)
         newselect.set_possible_types(solutions)
         # full sub-query
         aliases = [VariableRef(select.get_variable(avar.name, i))
@@ -207,9 +207,18 @@
                     if not vref in groups:
                         groups.append(vref)
 
-def fix_selection(rqlst, selectedidx, needwrap, sorts, groups, having):
-    if sorts:
+def fix_selection_and_group(rqlst, selectedidx, needwrap, selectsortterms,
+                            sorts, groups, having):
+    if selectsortterms and sorts:
         sort_term_selection(sorts, selectedidx, rqlst, not needwrap and groups)
+    if sorts and groups:
+        # when a query is grouped, ensure sort terms are grouped as well
+        for sortterm in sorts:
+            term = sortterm.term
+            if not isinstance(term, Constant):
+                for vref in term.iget_nodes(VariableRef):
+                    if not vref in groups:
+                        groups.append(vref)
     if needwrap:
         if groups:
             for vref in groups:
@@ -410,8 +419,8 @@
                                         outerselection, groups)
             else:
                 outerselectidx = selectidx[:]
-        fix_selection(select, selectidx, needwrap,
-                      selectsortterms and sorts, groups, having)
+        fix_selection_and_group(select, selectidx, needwrap,
+                                selectsortterms, sorts, groups, having)
         if needwrap:
             fselectidx = outerselectidx
             fneedwrap = len(outerselection) != len(origselection)
@@ -907,7 +916,7 @@
             elif not lhsvar.name in self._varmap:
                 # join on entities instead of etype's table to get result for
                 # external entities on multisources configurations
-                ealias = lhsvar._q_sqltable = lhsvar.name
+                ealias = lhsvar._q_sqltable = '_' + lhsvar.name
                 jointo = lhsvar._q_sql = '%s.eid' % ealias
                 self.add_table('entities AS %s' % ealias, ealias)
                 if not lhsvar._q_invariant or len(lhsvar.stinfo['possibletypes']) == 1:
@@ -1029,7 +1038,7 @@
             # since variable is invariant, we know we won't found final relation
             principal = variable.stinfo['principal']
             if principal is None:
-                vtablename = variable.name
+                vtablename = '_' + variable.name
                 self.add_table('entities AS %s' % vtablename, vtablename)
                 sql = '%s.eid' % vtablename
                 if variable.stinfo['typerels']:
@@ -1089,20 +1098,20 @@
             scope = -1
         try:
             sql = self._varmap[var.name]
-            table = sql.split('.', 1)[0]
+            tablealias = sql.split('.', 1)[0]
             if scope < 0:
-                scope = self._varmap_table_scope(var.stmt, table)
-            self.add_table(table, scope=scope)
+                scope = self._varmap_table_scope(var.stmt, tablealias)
+            self.add_table(tablealias, scope=scope)
         except KeyError:
             etype = self._state.solution[var.name]
             # XXX this check should be moved in rql.stcheck
             if self.schema.eschema(etype).final:
                 raise BadRQLQuery(var.stmt.root)
-            table = var.name
-            sql = '%s.%seid' % (table, SQL_PREFIX)
-            self.add_table('%s%s AS %s' % (SQL_PREFIX, etype, table), table,
-                           scope=scope)
-        return sql, table
+            tablealias = '_' + var.name
+            sql = '%s.%seid' % (tablealias, SQL_PREFIX)
+            self.add_table('%s%s AS %s' % (SQL_PREFIX, etype, tablealias),
+                           tablealias, scope=scope)
+        return sql, tablealias
 
     def _inlined_var_sql(self, var, rtype):
         try:
--- a/server/test/unittest_repository.py	Mon Oct 19 20:22:01 2009 +0200
+++ b/server/test/unittest_repository.py	Wed Oct 21 17:32:20 2009 +0200
@@ -96,14 +96,13 @@
         self.assert_(repo.connect(u"barnabé", u"héhéhé".encode('UTF8')))
 
     def test_invalid_entity_rollback(self):
-        repo = self.repo
-        cnxid = repo.connect(self.admlogin, self.admpassword)
+        cnxid = self.repo.connect(self.admlogin, self.admpassword)
         # no group
-        repo.execute(cnxid, 'INSERT CWUser X: X login %(login)s, X upassword %(passwd)s',
-                     {'login': u"tutetute", 'passwd': 'tutetute'})
-        self.assertRaises(ValidationError, repo.commit, cnxid)
-        rset = repo.execute(cnxid, 'CWUser X WHERE X login "tutetute"')
-        self.assertEquals(rset.rowcount, 0)
+        self.repo.execute(cnxid,
+                          'INSERT CWUser X: X login %(login)s, X upassword %(passwd)s',
+                          {'login': u"tutetute", 'passwd': 'tutetute'})
+        self.assertRaises(ValidationError, self.repo.commit, cnxid)
+        self.failIf(self.repo.execute(cnxid, 'CWUser X WHERE X login "tutetute"'))
 
     def test_close(self):
         repo = self.repo
@@ -212,7 +211,7 @@
                                if not r.type in ('eid', 'is', 'is_instance_of', 'identity',
                                                  'creation_date', 'modification_date', 'cwuri',
                                                  'owned_by', 'created_by')],
-                              ['relation_type', 'from_entity', 'in_basket', 'to_entity', 'constrained_by',
+                              ['relation_type', 'from_entity', 'to_entity', 'in_basket', 'constrained_by',
                                'cardinality', 'ordernum',
                                'indexed', 'fulltextindexed', 'internationalizable',
                                'defaultval', 'description', 'description_format'])
--- a/server/test/unittest_rql2sql.py	Mon Oct 19 20:22:01 2009 +0200
+++ b/server/test/unittest_rql2sql.py	Wed Oct 21 17:32:20 2009 +0200
@@ -39,111 +39,115 @@
 
 PARSER = [
     (r"Personne P WHERE P nom 'Zig\'oto';",
-     '''SELECT P.cw_eid
-FROM cw_Personne AS P
-WHERE P.cw_nom=Zig\'oto'''),
+     '''SELECT _P.cw_eid
+FROM cw_Personne AS _P
+WHERE _P.cw_nom=Zig\'oto'''),
 
     (r'Personne P WHERE P nom ~= "Zig\"oto%";',
-     '''SELECT P.cw_eid
-FROM cw_Personne AS P
-WHERE P.cw_nom ILIKE Zig"oto%'''),
+     '''SELECT _P.cw_eid
+FROM cw_Personne AS _P
+WHERE _P.cw_nom ILIKE Zig"oto%'''),
     ]
 
 BASIC = [
 
+    ("Any AS WHERE AS is Affaire",
+     '''SELECT _AS.cw_eid
+FROM cw_Affaire AS _AS'''),
+
     ("Any X WHERE X is Affaire",
-     '''SELECT X.cw_eid
-FROM cw_Affaire AS X'''),
+     '''SELECT _X.cw_eid
+FROM cw_Affaire AS _X'''),
 
     ("Any X WHERE X eid 0",
      '''SELECT 0'''),
 
     ("Personne P",
-     '''SELECT P.cw_eid
-FROM cw_Personne AS P'''),
+     '''SELECT _P.cw_eid
+FROM cw_Personne AS _P'''),
 
     ("Personne P WHERE P test TRUE",
-     '''SELECT P.cw_eid
-FROM cw_Personne AS P
-WHERE P.cw_test=TRUE'''),
+     '''SELECT _P.cw_eid
+FROM cw_Personne AS _P
+WHERE _P.cw_test=TRUE'''),
 
     ("Personne P WHERE P test false",
-     '''SELECT P.cw_eid
-FROM cw_Personne AS P
-WHERE P.cw_test=FALSE'''),
+     '''SELECT _P.cw_eid
+FROM cw_Personne AS _P
+WHERE _P.cw_test=FALSE'''),
 
     ("Personne P WHERE P eid -1",
      '''SELECT -1'''),
 
     ("Personne P LIMIT 20 OFFSET 10",
-     '''SELECT P.cw_eid
-FROM cw_Personne AS P
+     '''SELECT _P.cw_eid
+FROM cw_Personne AS _P
 LIMIT 20
 OFFSET 10'''),
 
     ("Personne P WHERE S is Societe, P travaille S, S nom 'Logilab';",
      '''SELECT rel_travaille0.eid_from
-FROM cw_Societe AS S, travaille_relation AS rel_travaille0
-WHERE rel_travaille0.eid_to=S.cw_eid AND S.cw_nom=Logilab'''),
+FROM cw_Societe AS _S, travaille_relation AS rel_travaille0
+WHERE rel_travaille0.eid_to=_S.cw_eid AND _S.cw_nom=Logilab'''),
 
     ("Personne P WHERE P concerne A, A concerne S, S nom 'Logilab', S is Societe;",
      '''SELECT rel_concerne0.eid_from
-FROM concerne_relation AS rel_concerne0, concerne_relation AS rel_concerne1, cw_Societe AS S
-WHERE rel_concerne0.eid_to=rel_concerne1.eid_from AND rel_concerne1.eid_to=S.cw_eid AND S.cw_nom=Logilab'''),
+FROM concerne_relation AS rel_concerne0, concerne_relation AS rel_concerne1, cw_Societe AS _S
+WHERE rel_concerne0.eid_to=rel_concerne1.eid_from AND rel_concerne1.eid_to=_S.cw_eid AND _S.cw_nom=Logilab'''),
 
     ("Note N WHERE X evaluee N, X nom 'Logilab';",
      '''SELECT rel_evaluee0.eid_to
-FROM cw_Division AS X, evaluee_relation AS rel_evaluee0
-WHERE rel_evaluee0.eid_from=X.cw_eid AND X.cw_nom=Logilab
+FROM cw_Division AS _X, evaluee_relation AS rel_evaluee0
+WHERE rel_evaluee0.eid_from=_X.cw_eid AND _X.cw_nom=Logilab
 UNION ALL
 SELECT rel_evaluee0.eid_to
-FROM cw_Personne AS X, evaluee_relation AS rel_evaluee0
-WHERE rel_evaluee0.eid_from=X.cw_eid AND X.cw_nom=Logilab
+FROM cw_Personne AS _X, evaluee_relation AS rel_evaluee0
+WHERE rel_evaluee0.eid_from=_X.cw_eid AND _X.cw_nom=Logilab
 UNION ALL
 SELECT rel_evaluee0.eid_to
-FROM cw_Societe AS X, evaluee_relation AS rel_evaluee0
-WHERE rel_evaluee0.eid_from=X.cw_eid AND X.cw_nom=Logilab
+FROM cw_Societe AS _X, evaluee_relation AS rel_evaluee0
+WHERE rel_evaluee0.eid_from=_X.cw_eid AND _X.cw_nom=Logilab
 UNION ALL
 SELECT rel_evaluee0.eid_to
-FROM cw_SubDivision AS X, evaluee_relation AS rel_evaluee0
-WHERE rel_evaluee0.eid_from=X.cw_eid AND X.cw_nom=Logilab'''),
+FROM cw_SubDivision AS _X, evaluee_relation AS rel_evaluee0
+WHERE rel_evaluee0.eid_from=_X.cw_eid AND _X.cw_nom=Logilab'''),
 
     ("Note N WHERE X evaluee N, X nom in ('Logilab', 'Caesium');",
      '''SELECT rel_evaluee0.eid_to
-FROM cw_Division AS X, evaluee_relation AS rel_evaluee0
-WHERE rel_evaluee0.eid_from=X.cw_eid AND X.cw_nom IN(Logilab, Caesium)
+FROM cw_Division AS _X, evaluee_relation AS rel_evaluee0
+WHERE rel_evaluee0.eid_from=_X.cw_eid AND _X.cw_nom IN(Logilab, Caesium)
 UNION ALL
 SELECT rel_evaluee0.eid_to
-FROM cw_Personne AS X, evaluee_relation AS rel_evaluee0
-WHERE rel_evaluee0.eid_from=X.cw_eid AND X.cw_nom IN(Logilab, Caesium)
+FROM cw_Personne AS _X, evaluee_relation AS rel_evaluee0
+WHERE rel_evaluee0.eid_from=_X.cw_eid AND _X.cw_nom IN(Logilab, Caesium)
 UNION ALL
 SELECT rel_evaluee0.eid_to
-FROM cw_Societe AS X, evaluee_relation AS rel_evaluee0
-WHERE rel_evaluee0.eid_from=X.cw_eid AND X.cw_nom IN(Logilab, Caesium)
+FROM cw_Societe AS _X, evaluee_relation AS rel_evaluee0
+WHERE rel_evaluee0.eid_from=_X.cw_eid AND _X.cw_nom IN(Logilab, Caesium)
 UNION ALL
 SELECT rel_evaluee0.eid_to
-FROM cw_SubDivision AS X, evaluee_relation AS rel_evaluee0
-WHERE rel_evaluee0.eid_from=X.cw_eid AND X.cw_nom IN(Logilab, Caesium)'''),
+FROM cw_SubDivision AS _X, evaluee_relation AS rel_evaluee0
+WHERE rel_evaluee0.eid_from=_X.cw_eid AND _X.cw_nom IN(Logilab, Caesium)'''),
 
     ("Any X WHERE X creation_date TODAY, X is Affaire",
-     '''SELECT X.cw_eid
-FROM cw_Affaire AS X
-WHERE DATE(X.cw_creation_date)=CURRENT_DATE'''),
+     '''SELECT _X.cw_eid
+FROM cw_Affaire AS _X
+WHERE DATE(_X.cw_creation_date)=CURRENT_DATE'''),
 
     ("Any N WHERE G is CWGroup, G name N, E eid 12, E read_permission G",
-     '''SELECT G.cw_name
-FROM cw_CWGroup AS G, read_permission_relation AS rel_read_permission0
-WHERE rel_read_permission0.eid_from=12 AND rel_read_permission0.eid_to=G.cw_eid'''),
+     '''SELECT _G.cw_name
+FROM cw_CWGroup AS _G, read_permission_relation AS rel_read_permission0
+WHERE rel_read_permission0.eid_from=12 AND rel_read_permission0.eid_to=_G.cw_eid'''),
 
     ('Any Y WHERE U login "admin", U login Y', # stupid but valid...
-     """SELECT U.cw_login
-FROM cw_CWUser AS U
-WHERE U.cw_login=admin"""),
+     """SELECT _U.cw_login
+FROM cw_CWUser AS _U
+WHERE _U.cw_login=admin"""),
 
     ('Any T WHERE T tags X, X is State',
      '''SELECT rel_tags0.eid_from
-FROM cw_State AS X, tags_relation AS rel_tags0
-WHERE rel_tags0.eid_to=X.cw_eid'''),
+FROM cw_State AS _X, tags_relation AS rel_tags0
+WHERE rel_tags0.eid_to=_X.cw_eid'''),
 
     ('Any X,Y WHERE X eid 0, Y eid 1, X concerne Y',
      '''SELECT 0, 1
@@ -152,39 +156,39 @@
 
     ("Any X WHERE X prenom 'lulu',"
      "EXISTS(X owned_by U, U in_group G, G name 'lulufanclub' OR G name 'managers');",
-     '''SELECT X.cw_eid
-FROM cw_Personne AS X
-WHERE X.cw_prenom=lulu AND EXISTS(SELECT 1 FROM owned_by_relation AS rel_owned_by0, in_group_relation AS rel_in_group1, cw_CWGroup AS G WHERE rel_owned_by0.eid_from=X.cw_eid AND rel_in_group1.eid_from=rel_owned_by0.eid_to AND rel_in_group1.eid_to=G.cw_eid AND ((G.cw_name=lulufanclub) OR (G.cw_name=managers)))'''),
+     '''SELECT _X.cw_eid
+FROM cw_Personne AS _X
+WHERE _X.cw_prenom=lulu AND EXISTS(SELECT 1 FROM owned_by_relation AS rel_owned_by0, in_group_relation AS rel_in_group1, cw_CWGroup AS _G WHERE rel_owned_by0.eid_from=_X.cw_eid AND rel_in_group1.eid_from=rel_owned_by0.eid_to AND rel_in_group1.eid_to=_G.cw_eid AND ((_G.cw_name=lulufanclub) OR (_G.cw_name=managers)))'''),
 
     ("Any X WHERE X prenom 'lulu',"
      "NOT EXISTS(X owned_by U, U in_group G, G name 'lulufanclub' OR G name 'managers');",
-     '''SELECT X.cw_eid
-FROM cw_Personne AS X
-WHERE X.cw_prenom=lulu AND NOT EXISTS(SELECT 1 FROM owned_by_relation AS rel_owned_by0, in_group_relation AS rel_in_group1, cw_CWGroup AS G WHERE rel_owned_by0.eid_from=X.cw_eid AND rel_in_group1.eid_from=rel_owned_by0.eid_to AND rel_in_group1.eid_to=G.cw_eid AND ((G.cw_name=lulufanclub) OR (G.cw_name=managers)))'''),
+     '''SELECT _X.cw_eid
+FROM cw_Personne AS _X
+WHERE _X.cw_prenom=lulu AND NOT EXISTS(SELECT 1 FROM owned_by_relation AS rel_owned_by0, in_group_relation AS rel_in_group1, cw_CWGroup AS _G WHERE rel_owned_by0.eid_from=_X.cw_eid AND rel_in_group1.eid_from=rel_owned_by0.eid_to AND rel_in_group1.eid_to=_G.cw_eid AND ((_G.cw_name=lulufanclub) OR (_G.cw_name=managers)))'''),
 ]
 
 ADVANCED= [
     ("Societe S WHERE S nom 'Logilab' OR S nom 'Caesium'",
-     '''SELECT S.cw_eid
-FROM cw_Societe AS S
-WHERE ((S.cw_nom=Logilab) OR (S.cw_nom=Caesium))'''),
+     '''SELECT _S.cw_eid
+FROM cw_Societe AS _S
+WHERE ((_S.cw_nom=Logilab) OR (_S.cw_nom=Caesium))'''),
 
     ('Any X WHERE X nom "toto", X eid IN (9700, 9710, 1045, 674)',
-    '''SELECT X.cw_eid
-FROM cw_Division AS X
-WHERE X.cw_nom=toto AND X.cw_eid IN(9700, 9710, 1045, 674)
+    '''SELECT _X.cw_eid
+FROM cw_Division AS _X
+WHERE _X.cw_nom=toto AND _X.cw_eid IN(9700, 9710, 1045, 674)
 UNION ALL
-SELECT X.cw_eid
-FROM cw_Personne AS X
-WHERE X.cw_nom=toto AND X.cw_eid IN(9700, 9710, 1045, 674)
+SELECT _X.cw_eid
+FROM cw_Personne AS _X
+WHERE _X.cw_nom=toto AND _X.cw_eid IN(9700, 9710, 1045, 674)
 UNION ALL
-SELECT X.cw_eid
-FROM cw_Societe AS X
-WHERE X.cw_nom=toto AND X.cw_eid IN(9700, 9710, 1045, 674)
+SELECT _X.cw_eid
+FROM cw_Societe AS _X
+WHERE _X.cw_nom=toto AND _X.cw_eid IN(9700, 9710, 1045, 674)
 UNION ALL
-SELECT X.cw_eid
-FROM cw_SubDivision AS X
-WHERE X.cw_nom=toto AND X.cw_eid IN(9700, 9710, 1045, 674)'''),
+SELECT _X.cw_eid
+FROM cw_SubDivision AS _X
+WHERE _X.cw_nom=toto AND _X.cw_eid IN(9700, 9710, 1045, 674)'''),
 
     ('Any Y, COUNT(N) GROUPBY Y WHERE Y evaluee N;',
      '''SELECT rel_evaluee0.eid_from, COUNT(rel_evaluee0.eid_to)
@@ -192,34 +196,34 @@
 GROUP BY rel_evaluee0.eid_from'''),
 
     ("Any X WHERE X concerne B or C concerne X",
-     '''SELECT X.cw_eid
-FROM concerne_relation AS rel_concerne0, concerne_relation AS rel_concerne1, cw_Affaire AS X
-WHERE ((rel_concerne0.eid_from=X.cw_eid) OR (rel_concerne1.eid_to=X.cw_eid))'''),
+     '''SELECT _X.cw_eid
+FROM concerne_relation AS rel_concerne0, concerne_relation AS rel_concerne1, cw_Affaire AS _X
+WHERE ((rel_concerne0.eid_from=_X.cw_eid) OR (rel_concerne1.eid_to=_X.cw_eid))'''),
 
     ("Any X WHERE X travaille S or X concerne A",
-     '''SELECT X.cw_eid
-FROM concerne_relation AS rel_concerne1, cw_Personne AS X, travaille_relation AS rel_travaille0
-WHERE ((rel_travaille0.eid_from=X.cw_eid) OR (rel_concerne1.eid_from=X.cw_eid))'''),
+     '''SELECT _X.cw_eid
+FROM concerne_relation AS rel_concerne1, cw_Personne AS _X, travaille_relation AS rel_travaille0
+WHERE ((rel_travaille0.eid_from=_X.cw_eid) OR (rel_concerne1.eid_from=_X.cw_eid))'''),
 
     ("Any N WHERE A evaluee N or N ecrit_par P",
-     '''SELECT N.cw_eid
-FROM cw_Note AS N, evaluee_relation AS rel_evaluee0
-WHERE ((rel_evaluee0.eid_to=N.cw_eid) OR (N.cw_ecrit_par IS NOT NULL))'''),
+     '''SELECT _N.cw_eid
+FROM cw_Note AS _N, evaluee_relation AS rel_evaluee0
+WHERE ((rel_evaluee0.eid_to=_N.cw_eid) OR (_N.cw_ecrit_par IS NOT NULL))'''),
 
     ("Any N WHERE A evaluee N or EXISTS(N todo_by U)",
-     '''SELECT N.cw_eid
-FROM cw_Note AS N, evaluee_relation AS rel_evaluee0
-WHERE ((rel_evaluee0.eid_to=N.cw_eid) OR (EXISTS(SELECT 1 FROM todo_by_relation AS rel_todo_by1 WHERE rel_todo_by1.eid_from=N.cw_eid)))'''),
+     '''SELECT _N.cw_eid
+FROM cw_Note AS _N, evaluee_relation AS rel_evaluee0
+WHERE ((rel_evaluee0.eid_to=_N.cw_eid) OR (EXISTS(SELECT 1 FROM todo_by_relation AS rel_todo_by1 WHERE rel_todo_by1.eid_from=_N.cw_eid)))'''),
 
     ("Any N WHERE A evaluee N or N todo_by U",
-     '''SELECT N.cw_eid
-FROM cw_Note AS N, evaluee_relation AS rel_evaluee0, todo_by_relation AS rel_todo_by1
-WHERE ((rel_evaluee0.eid_to=N.cw_eid) OR (rel_todo_by1.eid_from=N.cw_eid))'''),
+     '''SELECT _N.cw_eid
+FROM cw_Note AS _N, evaluee_relation AS rel_evaluee0, todo_by_relation AS rel_todo_by1
+WHERE ((rel_evaluee0.eid_to=_N.cw_eid) OR (rel_todo_by1.eid_from=_N.cw_eid))'''),
 
     ("Any X WHERE X concerne B or C concerne X, B eid 12, C eid 13",
-     '''SELECT X.cw_eid
-FROM concerne_relation AS rel_concerne0, concerne_relation AS rel_concerne1, cw_Affaire AS X
-WHERE ((rel_concerne0.eid_from=X.cw_eid AND rel_concerne0.eid_to=12) OR (rel_concerne1.eid_from=13 AND rel_concerne1.eid_to=X.cw_eid))'''),
+     '''SELECT _X.cw_eid
+FROM concerne_relation AS rel_concerne0, concerne_relation AS rel_concerne1, cw_Affaire AS _X
+WHERE ((rel_concerne0.eid_from=_X.cw_eid AND rel_concerne0.eid_to=12) OR (rel_concerne1.eid_from=13 AND rel_concerne1.eid_to=_X.cw_eid))'''),
 
     ('Any X WHERE X created_by U, X concerne B OR C concerne X, B eid 12, C eid 13',
      '''SELECT rel_created_by0.eid_from
@@ -227,9 +231,9 @@
 WHERE ((rel_concerne1.eid_from=rel_created_by0.eid_from AND rel_concerne1.eid_to=12) OR (rel_concerne2.eid_from=13 AND rel_concerne2.eid_to=rel_created_by0.eid_from))'''),
 
     ('Any P WHERE P travaille_subdivision S1 OR P travaille_subdivision S2, S1 nom "logilab", S2 nom "caesium"',
-     '''SELECT P.cw_eid
-FROM cw_Personne AS P, cw_SubDivision AS S1, cw_SubDivision AS S2, travaille_subdivision_relation AS rel_travaille_subdivision0, travaille_subdivision_relation AS rel_travaille_subdivision1
-WHERE ((rel_travaille_subdivision0.eid_from=P.cw_eid AND rel_travaille_subdivision0.eid_to=S1.cw_eid) OR (rel_travaille_subdivision1.eid_from=P.cw_eid AND rel_travaille_subdivision1.eid_to=S2.cw_eid)) AND S1.cw_nom=logilab AND S2.cw_nom=caesium'''),
+     '''SELECT _P.cw_eid
+FROM cw_Personne AS _P, cw_SubDivision AS _S1, cw_SubDivision AS _S2, travaille_subdivision_relation AS rel_travaille_subdivision0, travaille_subdivision_relation AS rel_travaille_subdivision1
+WHERE ((rel_travaille_subdivision0.eid_from=_P.cw_eid AND rel_travaille_subdivision0.eid_to=_S1.cw_eid) OR (rel_travaille_subdivision1.eid_from=_P.cw_eid AND rel_travaille_subdivision1.eid_to=_S2.cw_eid)) AND _S1.cw_nom=logilab AND _S2.cw_nom=caesium'''),
 
     ('Any X WHERE T tags X',
      '''SELECT rel_tags0.eid_to
@@ -241,31 +245,31 @@
 WHERE rel_in_basket0.eid_to=12'''),
 
     ('Any SEN,RN,OEN WHERE X from_entity SE, SE eid 44, X relation_type R, R eid 139, X to_entity OE, OE eid 42, R name RN, SE name SEN, OE name OEN',
-     '''SELECT SE.cw_name, R.cw_name, OE.cw_name
-FROM cw_CWAttribute AS X, cw_CWEType AS OE, cw_CWEType AS SE, cw_CWRType AS R
-WHERE X.cw_from_entity=44 AND SE.cw_eid=44 AND X.cw_relation_type=139 AND R.cw_eid=139 AND X.cw_to_entity=42 AND OE.cw_eid=42
+     '''SELECT _SE.cw_name, _R.cw_name, _OE.cw_name
+FROM cw_CWAttribute AS _X, cw_CWEType AS _OE, cw_CWEType AS _SE, cw_CWRType AS _R
+WHERE _X.cw_from_entity=44 AND _SE.cw_eid=44 AND _X.cw_relation_type=139 AND _R.cw_eid=139 AND _X.cw_to_entity=42 AND _OE.cw_eid=42
 UNION ALL
-SELECT SE.cw_name, R.cw_name, OE.cw_name
-FROM cw_CWEType AS OE, cw_CWEType AS SE, cw_CWRType AS R, cw_CWRelation AS X
-WHERE X.cw_from_entity=44 AND SE.cw_eid=44 AND X.cw_relation_type=139 AND R.cw_eid=139 AND X.cw_to_entity=42 AND OE.cw_eid=42'''),
+SELECT _SE.cw_name, _R.cw_name, _OE.cw_name
+FROM cw_CWEType AS _OE, cw_CWEType AS _SE, cw_CWRType AS _R, cw_CWRelation AS _X
+WHERE _X.cw_from_entity=44 AND _SE.cw_eid=44 AND _X.cw_relation_type=139 AND _R.cw_eid=139 AND _X.cw_to_entity=42 AND _OE.cw_eid=42'''),
 
     # Any O WHERE NOT S corrected_in O, S eid %(x)s, S concerns P, O version_of P, O in_state ST, NOT ST name "published", O modification_date MTIME ORDERBY MTIME DESC LIMIT 9
     ('Any O WHERE NOT S ecrit_par O, S eid 1, S inline1 P, O inline2 P',
-     '''SELECT O.cw_eid
-FROM cw_Note AS S, cw_Personne AS O
-WHERE NOT EXISTS(SELECT 1 WHERE S.cw_ecrit_par=O.cw_eid) AND S.cw_eid=1 AND O.cw_inline2=S.cw_inline1'''),
+     '''SELECT _O.cw_eid
+FROM cw_Note AS _S, cw_Personne AS _O
+WHERE NOT EXISTS(SELECT 1 WHERE _S.cw_ecrit_par=_O.cw_eid) AND _S.cw_eid=1 AND _O.cw_inline2=_S.cw_inline1'''),
 
     ('DISTINCT Any S ORDERBY stockproc(SI) WHERE NOT S ecrit_par O, S para SI',
-     '''SELECT T1.C0 FROM (SELECT DISTINCT S.cw_eid AS C0, STOCKPROC(S.cw_para) AS C1
-FROM cw_Note AS S
-WHERE S.cw_ecrit_par IS NULL
+     '''SELECT T1.C0 FROM (SELECT DISTINCT _S.cw_eid AS C0, STOCKPROC(_S.cw_para) AS C1
+FROM cw_Note AS _S
+WHERE _S.cw_ecrit_par IS NULL
 ORDER BY 2) AS T1'''),
 
     ('Any N WHERE N todo_by U, N is Note, U eid 2, N filed_under T, T eid 3',
      # N would actually be invarient if U eid 2 had given a specific type to U
-     '''SELECT N.cw_eid
-FROM cw_Note AS N, filed_under_relation AS rel_filed_under1, todo_by_relation AS rel_todo_by0
-WHERE rel_todo_by0.eid_from=N.cw_eid AND rel_todo_by0.eid_to=2 AND rel_filed_under1.eid_from=N.cw_eid AND rel_filed_under1.eid_to=3'''),
+     '''SELECT _N.cw_eid
+FROM cw_Note AS _N, filed_under_relation AS rel_filed_under1, todo_by_relation AS rel_todo_by0
+WHERE rel_todo_by0.eid_from=_N.cw_eid AND rel_todo_by0.eid_to=2 AND rel_filed_under1.eid_from=_N.cw_eid AND rel_filed_under1.eid_to=3'''),
 
     ('Any N WHERE N todo_by U, U eid 2, P evaluee N, P eid 3',
      '''SELECT rel_evaluee1.eid_to
@@ -279,254 +283,254 @@
 WHERE rel_owned_by0.eid_from=1 AND NOT EXISTS(SELECT 1 FROM owned_by_relation AS rel_owned_by1 WHERE rel_owned_by1.eid_from=2 AND rel_owned_by0.eid_to=rel_owned_by1.eid_to)'''),
 
     ('Any GN WHERE X in_group G, G name GN, (G name "managers" OR EXISTS(X copain T, T login in ("comme", "cochon")))',
-     '''SELECT G.cw_name
-FROM cw_CWGroup AS G, in_group_relation AS rel_in_group0
-WHERE rel_in_group0.eid_to=G.cw_eid AND ((G.cw_name=managers) OR (EXISTS(SELECT 1 FROM copain_relation AS rel_copain1, cw_CWUser AS T WHERE rel_copain1.eid_from=rel_in_group0.eid_from AND rel_copain1.eid_to=T.cw_eid AND T.cw_login IN(comme, cochon))))'''),
+     '''SELECT _G.cw_name
+FROM cw_CWGroup AS _G, in_group_relation AS rel_in_group0
+WHERE rel_in_group0.eid_to=_G.cw_eid AND ((_G.cw_name=managers) OR (EXISTS(SELECT 1 FROM copain_relation AS rel_copain1, cw_CWUser AS _T WHERE rel_copain1.eid_from=rel_in_group0.eid_from AND rel_copain1.eid_to=_T.cw_eid AND _T.cw_login IN(comme, cochon))))'''),
 
     ('Any C WHERE C is Card, EXISTS(X documented_by C)',
-      """SELECT C.cw_eid
-FROM cw_Card AS C
-WHERE EXISTS(SELECT 1 FROM documented_by_relation AS rel_documented_by0 WHERE rel_documented_by0.eid_to=C.cw_eid)"""),
+      """SELECT _C.cw_eid
+FROM cw_Card AS _C
+WHERE EXISTS(SELECT 1 FROM documented_by_relation AS rel_documented_by0 WHERE rel_documented_by0.eid_to=_C.cw_eid)"""),
 
     ('Any C WHERE C is Card, EXISTS(X documented_by C, X eid 12)',
-      """SELECT C.cw_eid
-FROM cw_Card AS C
-WHERE EXISTS(SELECT 1 FROM documented_by_relation AS rel_documented_by0 WHERE rel_documented_by0.eid_from=12 AND rel_documented_by0.eid_to=C.cw_eid)"""),
+      """SELECT _C.cw_eid
+FROM cw_Card AS _C
+WHERE EXISTS(SELECT 1 FROM documented_by_relation AS rel_documented_by0 WHERE rel_documented_by0.eid_from=12 AND rel_documented_by0.eid_to=_C.cw_eid)"""),
 
     ('Any T WHERE C is Card, C title T, EXISTS(X documented_by C, X eid 12)',
-      """SELECT C.cw_title
-FROM cw_Card AS C
-WHERE EXISTS(SELECT 1 FROM documented_by_relation AS rel_documented_by0 WHERE rel_documented_by0.eid_from=12 AND rel_documented_by0.eid_to=C.cw_eid)"""),
+      """SELECT _C.cw_title
+FROM cw_Card AS _C
+WHERE EXISTS(SELECT 1 FROM documented_by_relation AS rel_documented_by0 WHERE rel_documented_by0.eid_from=12 AND rel_documented_by0.eid_to=_C.cw_eid)"""),
 
     ('Any GN,L WHERE X in_group G, X login L, G name GN, EXISTS(X copain T, T login L, T login IN("comme", "cochon"))',
-     '''SELECT G.cw_name, X.cw_login
-FROM cw_CWGroup AS G, cw_CWUser AS X, in_group_relation AS rel_in_group0
-WHERE rel_in_group0.eid_from=X.cw_eid AND rel_in_group0.eid_to=G.cw_eid AND EXISTS(SELECT 1 FROM copain_relation AS rel_copain1, cw_CWUser AS T WHERE rel_copain1.eid_from=X.cw_eid AND rel_copain1.eid_to=T.cw_eid AND T.cw_login=X.cw_login AND T.cw_login IN(comme, cochon))'''),
+     '''SELECT _G.cw_name, _X.cw_login
+FROM cw_CWGroup AS _G, cw_CWUser AS _X, in_group_relation AS rel_in_group0
+WHERE rel_in_group0.eid_from=_X.cw_eid AND rel_in_group0.eid_to=_G.cw_eid AND EXISTS(SELECT 1 FROM copain_relation AS rel_copain1, cw_CWUser AS _T WHERE rel_copain1.eid_from=_X.cw_eid AND rel_copain1.eid_to=_T.cw_eid AND _T.cw_login=_X.cw_login AND _T.cw_login IN(comme, cochon))'''),
 
     ('Any X,S, MAX(T) GROUPBY X,S ORDERBY S WHERE X is CWUser, T tags X, S eid IN(32), X in_state S',
-     '''SELECT X.cw_eid, 32, MAX(rel_tags0.eid_from)
-FROM cw_CWUser AS X, tags_relation AS rel_tags0
-WHERE rel_tags0.eid_to=X.cw_eid AND X.cw_in_state=32
-GROUP BY X.cw_eid'''),
+     '''SELECT _X.cw_eid, 32, MAX(rel_tags0.eid_from)
+FROM cw_CWUser AS _X, tags_relation AS rel_tags0
+WHERE rel_tags0.eid_to=_X.cw_eid AND _X.cw_in_state=32
+GROUP BY _X.cw_eid'''),
 
     ('Any COUNT(S),CS GROUPBY CS ORDERBY 1 DESC LIMIT 10 WHERE S is Affaire, C is Societe, S concerne C, C nom CS, (EXISTS(S owned_by 1)) OR (EXISTS(S documented_by N, N title "published"))',
-     '''SELECT COUNT(rel_concerne0.eid_from), C.cw_nom
-FROM concerne_relation AS rel_concerne0, cw_Societe AS C
-WHERE rel_concerne0.eid_to=C.cw_eid AND ((EXISTS(SELECT 1 FROM owned_by_relation AS rel_owned_by1 WHERE rel_concerne0.eid_from=rel_owned_by1.eid_from AND rel_owned_by1.eid_to=1)) OR (EXISTS(SELECT 1 FROM documented_by_relation AS rel_documented_by2, cw_Card AS N WHERE rel_concerne0.eid_from=rel_documented_by2.eid_from AND rel_documented_by2.eid_to=N.cw_eid AND N.cw_title=published)))
-GROUP BY C.cw_nom
+     '''SELECT COUNT(rel_concerne0.eid_from), _C.cw_nom
+FROM concerne_relation AS rel_concerne0, cw_Societe AS _C
+WHERE rel_concerne0.eid_to=_C.cw_eid AND ((EXISTS(SELECT 1 FROM owned_by_relation AS rel_owned_by1 WHERE rel_concerne0.eid_from=rel_owned_by1.eid_from AND rel_owned_by1.eid_to=1)) OR (EXISTS(SELECT 1 FROM documented_by_relation AS rel_documented_by2, cw_Card AS _N WHERE rel_concerne0.eid_from=rel_documented_by2.eid_from AND rel_documented_by2.eid_to=_N.cw_eid AND _N.cw_title=published)))
+GROUP BY _C.cw_nom
 ORDER BY 1 DESC
 LIMIT 10'''),
 
     ('Any X WHERE Y evaluee X, Y is CWUser',
      '''SELECT rel_evaluee0.eid_to
-FROM cw_CWUser AS Y, evaluee_relation AS rel_evaluee0
-WHERE rel_evaluee0.eid_from=Y.cw_eid'''),
+FROM cw_CWUser AS _Y, evaluee_relation AS rel_evaluee0
+WHERE rel_evaluee0.eid_from=_Y.cw_eid'''),
 
     ('Any L WHERE X login "admin", X identity Y, Y login L',
-     '''SELECT Y.cw_login
-FROM cw_CWUser AS X, cw_CWUser AS Y
-WHERE X.cw_login=admin AND X.cw_eid=Y.cw_eid'''),
+     '''SELECT _Y.cw_login
+FROM cw_CWUser AS _X, cw_CWUser AS _Y
+WHERE _X.cw_login=admin AND _X.cw_eid=_Y.cw_eid'''),
 
     ('Any L WHERE X login "admin", NOT X identity Y, Y login L',
-     '''SELECT Y.cw_login
-FROM cw_CWUser AS X, cw_CWUser AS Y
-WHERE X.cw_login=admin AND NOT X.cw_eid=Y.cw_eid'''),
+     '''SELECT _Y.cw_login
+FROM cw_CWUser AS _X, cw_CWUser AS _Y
+WHERE _X.cw_login=admin AND NOT _X.cw_eid=_Y.cw_eid'''),
 
     ('Any L WHERE X login "admin", X identity Y?, Y login L',
-     '''SELECT Y.cw_login
-FROM cw_CWUser AS X LEFT OUTER JOIN cw_CWUser AS Y ON (X.cw_eid=Y.cw_eid)
-WHERE X.cw_login=admin'''),
+     '''SELECT _Y.cw_login
+FROM cw_CWUser AS _X LEFT OUTER JOIN cw_CWUser AS _Y ON (_X.cw_eid=_Y.cw_eid)
+WHERE _X.cw_login=admin'''),
 
     ('Any XN ORDERBY XN WHERE X name XN, X is IN (Basket,Folder,Tag)',
-     '''SELECT X.cw_name
-FROM cw_Basket AS X
+     '''SELECT _X.cw_name
+FROM cw_Basket AS _X
 UNION ALL
-SELECT X.cw_name
-FROM cw_Folder AS X
+SELECT _X.cw_name
+FROM cw_Folder AS _X
 UNION ALL
-SELECT X.cw_name
-FROM cw_Tag AS X
+SELECT _X.cw_name
+FROM cw_Tag AS _X
 ORDER BY 1'''),
 
     # DISTINCT, can use relation under exists scope as principal
     ('DISTINCT Any X,Y WHERE X name "CWGroup", Y eid IN(1, 2, 3), EXISTS(X read_permission Y)',
-     '''SELECT DISTINCT X.cw_eid, rel_read_permission0.eid_to
-FROM cw_CWEType AS X, read_permission_relation AS rel_read_permission0
-WHERE X.cw_name=CWGroup AND rel_read_permission0.eid_to IN(1, 2, 3) AND EXISTS(SELECT 1 WHERE rel_read_permission0.eid_from=X.cw_eid)
+     '''SELECT DISTINCT _X.cw_eid, rel_read_permission0.eid_to
+FROM cw_CWEType AS _X, read_permission_relation AS rel_read_permission0
+WHERE _X.cw_name=CWGroup AND rel_read_permission0.eid_to IN(1, 2, 3) AND EXISTS(SELECT 1 WHERE rel_read_permission0.eid_from=_X.cw_eid)
 UNION
-SELECT DISTINCT X.cw_eid, rel_read_permission0.eid_to
-FROM cw_CWRType AS X, read_permission_relation AS rel_read_permission0
-WHERE X.cw_name=CWGroup AND rel_read_permission0.eid_to IN(1, 2, 3) AND EXISTS(SELECT 1 WHERE rel_read_permission0.eid_from=X.cw_eid)'''),
+SELECT DISTINCT _X.cw_eid, rel_read_permission0.eid_to
+FROM cw_CWRType AS _X, read_permission_relation AS rel_read_permission0
+WHERE _X.cw_name=CWGroup AND rel_read_permission0.eid_to IN(1, 2, 3) AND EXISTS(SELECT 1 WHERE rel_read_permission0.eid_from=_X.cw_eid)'''),
 
     # no distinct, Y can't be invariant
     ('Any X,Y WHERE X name "CWGroup", Y eid IN(1, 2, 3), EXISTS(X read_permission Y)',
-     '''SELECT X.cw_eid, Y.cw_eid
-FROM cw_CWEType AS X, cw_CWGroup AS Y
-WHERE X.cw_name=CWGroup AND Y.cw_eid IN(1, 2, 3) AND EXISTS(SELECT 1 FROM read_permission_relation AS rel_read_permission0 WHERE rel_read_permission0.eid_from=X.cw_eid AND rel_read_permission0.eid_to=Y.cw_eid)
+     '''SELECT _X.cw_eid, _Y.cw_eid
+FROM cw_CWEType AS _X, cw_CWGroup AS _Y
+WHERE _X.cw_name=CWGroup AND _Y.cw_eid IN(1, 2, 3) AND EXISTS(SELECT 1 FROM read_permission_relation AS rel_read_permission0 WHERE rel_read_permission0.eid_from=_X.cw_eid AND rel_read_permission0.eid_to=_Y.cw_eid)
 UNION ALL
-SELECT X.cw_eid, Y.cw_eid
-FROM cw_CWEType AS X, cw_RQLExpression AS Y
-WHERE X.cw_name=CWGroup AND Y.cw_eid IN(1, 2, 3) AND EXISTS(SELECT 1 FROM read_permission_relation AS rel_read_permission0 WHERE rel_read_permission0.eid_from=X.cw_eid AND rel_read_permission0.eid_to=Y.cw_eid)
+SELECT _X.cw_eid, _Y.cw_eid
+FROM cw_CWEType AS _X, cw_RQLExpression AS _Y
+WHERE _X.cw_name=CWGroup AND _Y.cw_eid IN(1, 2, 3) AND EXISTS(SELECT 1 FROM read_permission_relation AS rel_read_permission0 WHERE rel_read_permission0.eid_from=_X.cw_eid AND rel_read_permission0.eid_to=_Y.cw_eid)
 UNION ALL
-SELECT X.cw_eid, Y.cw_eid
-FROM cw_CWGroup AS Y, cw_CWRType AS X
-WHERE X.cw_name=CWGroup AND Y.cw_eid IN(1, 2, 3) AND EXISTS(SELECT 1 FROM read_permission_relation AS rel_read_permission0 WHERE rel_read_permission0.eid_from=X.cw_eid AND rel_read_permission0.eid_to=Y.cw_eid)
+SELECT _X.cw_eid, _Y.cw_eid
+FROM cw_CWGroup AS _Y, cw_CWRType AS _X
+WHERE _X.cw_name=CWGroup AND _Y.cw_eid IN(1, 2, 3) AND EXISTS(SELECT 1 FROM read_permission_relation AS rel_read_permission0 WHERE rel_read_permission0.eid_from=_X.cw_eid AND rel_read_permission0.eid_to=_Y.cw_eid)
 UNION ALL
-SELECT X.cw_eid, Y.cw_eid
-FROM cw_CWRType AS X, cw_RQLExpression AS Y
-WHERE X.cw_name=CWGroup AND Y.cw_eid IN(1, 2, 3) AND EXISTS(SELECT 1 FROM read_permission_relation AS rel_read_permission0 WHERE rel_read_permission0.eid_from=X.cw_eid AND rel_read_permission0.eid_to=Y.cw_eid)'''),
+SELECT _X.cw_eid, _Y.cw_eid
+FROM cw_CWRType AS _X, cw_RQLExpression AS _Y
+WHERE _X.cw_name=CWGroup AND _Y.cw_eid IN(1, 2, 3) AND EXISTS(SELECT 1 FROM read_permission_relation AS rel_read_permission0 WHERE rel_read_permission0.eid_from=_X.cw_eid AND rel_read_permission0.eid_to=_Y.cw_eid)'''),
 
     # DISTINCT but NEGED exists, can't be invariant
     ('DISTINCT Any X,Y WHERE X name "CWGroup", Y eid IN(1, 2, 3), NOT EXISTS(X read_permission Y)',
-     '''SELECT DISTINCT X.cw_eid, Y.cw_eid
-FROM cw_CWEType AS X, cw_CWGroup AS Y
-WHERE X.cw_name=CWGroup AND Y.cw_eid IN(1, 2, 3) AND NOT EXISTS(SELECT 1 FROM read_permission_relation AS rel_read_permission0 WHERE rel_read_permission0.eid_from=X.cw_eid AND rel_read_permission0.eid_to=Y.cw_eid)
+     '''SELECT DISTINCT _X.cw_eid, _Y.cw_eid
+FROM cw_CWEType AS _X, cw_CWGroup AS _Y
+WHERE _X.cw_name=CWGroup AND _Y.cw_eid IN(1, 2, 3) AND NOT EXISTS(SELECT 1 FROM read_permission_relation AS rel_read_permission0 WHERE rel_read_permission0.eid_from=_X.cw_eid AND rel_read_permission0.eid_to=_Y.cw_eid)
 UNION
-SELECT DISTINCT X.cw_eid, Y.cw_eid
-FROM cw_CWEType AS X, cw_RQLExpression AS Y
-WHERE X.cw_name=CWGroup AND Y.cw_eid IN(1, 2, 3) AND NOT EXISTS(SELECT 1 FROM read_permission_relation AS rel_read_permission0 WHERE rel_read_permission0.eid_from=X.cw_eid AND rel_read_permission0.eid_to=Y.cw_eid)
+SELECT DISTINCT _X.cw_eid, _Y.cw_eid
+FROM cw_CWEType AS _X, cw_RQLExpression AS _Y
+WHERE _X.cw_name=CWGroup AND _Y.cw_eid IN(1, 2, 3) AND NOT EXISTS(SELECT 1 FROM read_permission_relation AS rel_read_permission0 WHERE rel_read_permission0.eid_from=_X.cw_eid AND rel_read_permission0.eid_to=_Y.cw_eid)
 UNION
-SELECT DISTINCT X.cw_eid, Y.cw_eid
-FROM cw_CWGroup AS Y, cw_CWRType AS X
-WHERE X.cw_name=CWGroup AND Y.cw_eid IN(1, 2, 3) AND NOT EXISTS(SELECT 1 FROM read_permission_relation AS rel_read_permission0 WHERE rel_read_permission0.eid_from=X.cw_eid AND rel_read_permission0.eid_to=Y.cw_eid)
+SELECT DISTINCT _X.cw_eid, _Y.cw_eid
+FROM cw_CWGroup AS _Y, cw_CWRType AS _X
+WHERE _X.cw_name=CWGroup AND _Y.cw_eid IN(1, 2, 3) AND NOT EXISTS(SELECT 1 FROM read_permission_relation AS rel_read_permission0 WHERE rel_read_permission0.eid_from=_X.cw_eid AND rel_read_permission0.eid_to=_Y.cw_eid)
 UNION
-SELECT DISTINCT X.cw_eid, Y.cw_eid
-FROM cw_CWRType AS X, cw_RQLExpression AS Y
-WHERE X.cw_name=CWGroup AND Y.cw_eid IN(1, 2, 3) AND NOT EXISTS(SELECT 1 FROM read_permission_relation AS rel_read_permission0 WHERE rel_read_permission0.eid_from=X.cw_eid AND rel_read_permission0.eid_to=Y.cw_eid)'''),
+SELECT DISTINCT _X.cw_eid, _Y.cw_eid
+FROM cw_CWRType AS _X, cw_RQLExpression AS _Y
+WHERE _X.cw_name=CWGroup AND _Y.cw_eid IN(1, 2, 3) AND NOT EXISTS(SELECT 1 FROM read_permission_relation AS rel_read_permission0 WHERE rel_read_permission0.eid_from=_X.cw_eid AND rel_read_permission0.eid_to=_Y.cw_eid)'''),
 
     # should generate the same query as above
     ('DISTINCT Any X,Y WHERE X name "CWGroup", Y eid IN(1, 2, 3), NOT X read_permission Y',
-     '''SELECT DISTINCT X.cw_eid, Y.cw_eid
-FROM cw_CWEType AS X, cw_CWGroup AS Y
-WHERE X.cw_name=CWGroup AND Y.cw_eid IN(1, 2, 3) AND NOT EXISTS(SELECT 1 FROM read_permission_relation AS rel_read_permission0 WHERE rel_read_permission0.eid_from=X.cw_eid AND rel_read_permission0.eid_to=Y.cw_eid)
+     '''SELECT DISTINCT _X.cw_eid, _Y.cw_eid
+FROM cw_CWEType AS _X, cw_CWGroup AS _Y
+WHERE _X.cw_name=CWGroup AND _Y.cw_eid IN(1, 2, 3) AND NOT EXISTS(SELECT 1 FROM read_permission_relation AS rel_read_permission0 WHERE rel_read_permission0.eid_from=_X.cw_eid AND rel_read_permission0.eid_to=_Y.cw_eid)
 UNION
-SELECT DISTINCT X.cw_eid, Y.cw_eid
-FROM cw_CWEType AS X, cw_RQLExpression AS Y
-WHERE X.cw_name=CWGroup AND Y.cw_eid IN(1, 2, 3) AND NOT EXISTS(SELECT 1 FROM read_permission_relation AS rel_read_permission0 WHERE rel_read_permission0.eid_from=X.cw_eid AND rel_read_permission0.eid_to=Y.cw_eid)
+SELECT DISTINCT _X.cw_eid, _Y.cw_eid
+FROM cw_CWEType AS _X, cw_RQLExpression AS _Y
+WHERE _X.cw_name=CWGroup AND _Y.cw_eid IN(1, 2, 3) AND NOT EXISTS(SELECT 1 FROM read_permission_relation AS rel_read_permission0 WHERE rel_read_permission0.eid_from=_X.cw_eid AND rel_read_permission0.eid_to=_Y.cw_eid)
 UNION
-SELECT DISTINCT X.cw_eid, Y.cw_eid
-FROM cw_CWGroup AS Y, cw_CWRType AS X
-WHERE X.cw_name=CWGroup AND Y.cw_eid IN(1, 2, 3) AND NOT EXISTS(SELECT 1 FROM read_permission_relation AS rel_read_permission0 WHERE rel_read_permission0.eid_from=X.cw_eid AND rel_read_permission0.eid_to=Y.cw_eid)
+SELECT DISTINCT _X.cw_eid, _Y.cw_eid
+FROM cw_CWGroup AS _Y, cw_CWRType AS _X
+WHERE _X.cw_name=CWGroup AND _Y.cw_eid IN(1, 2, 3) AND NOT EXISTS(SELECT 1 FROM read_permission_relation AS rel_read_permission0 WHERE rel_read_permission0.eid_from=_X.cw_eid AND rel_read_permission0.eid_to=_Y.cw_eid)
 UNION
-SELECT DISTINCT X.cw_eid, Y.cw_eid
-FROM cw_CWRType AS X, cw_RQLExpression AS Y
-WHERE X.cw_name=CWGroup AND Y.cw_eid IN(1, 2, 3) AND NOT EXISTS(SELECT 1 FROM read_permission_relation AS rel_read_permission0 WHERE rel_read_permission0.eid_from=X.cw_eid AND rel_read_permission0.eid_to=Y.cw_eid)'''),
+SELECT DISTINCT _X.cw_eid, _Y.cw_eid
+FROM cw_CWRType AS _X, cw_RQLExpression AS _Y
+WHERE _X.cw_name=CWGroup AND _Y.cw_eid IN(1, 2, 3) AND NOT EXISTS(SELECT 1 FROM read_permission_relation AS rel_read_permission0 WHERE rel_read_permission0.eid_from=_X.cw_eid AND rel_read_permission0.eid_to=_Y.cw_eid)'''),
 
     # neged relation, can't be inveriant
     ('Any X,Y WHERE X name "CWGroup", Y eid IN(1, 2, 3), NOT X read_permission Y',
-     '''SELECT X.cw_eid, Y.cw_eid
-FROM cw_CWEType AS X, cw_CWGroup AS Y
-WHERE X.cw_name=CWGroup AND Y.cw_eid IN(1, 2, 3) AND NOT EXISTS(SELECT 1 FROM read_permission_relation AS rel_read_permission0 WHERE rel_read_permission0.eid_from=X.cw_eid AND rel_read_permission0.eid_to=Y.cw_eid)
+     '''SELECT _X.cw_eid, _Y.cw_eid
+FROM cw_CWEType AS _X, cw_CWGroup AS _Y
+WHERE _X.cw_name=CWGroup AND _Y.cw_eid IN(1, 2, 3) AND NOT EXISTS(SELECT 1 FROM read_permission_relation AS rel_read_permission0 WHERE rel_read_permission0.eid_from=_X.cw_eid AND rel_read_permission0.eid_to=_Y.cw_eid)
 UNION ALL
-SELECT X.cw_eid, Y.cw_eid
-FROM cw_CWEType AS X, cw_RQLExpression AS Y
-WHERE X.cw_name=CWGroup AND Y.cw_eid IN(1, 2, 3) AND NOT EXISTS(SELECT 1 FROM read_permission_relation AS rel_read_permission0 WHERE rel_read_permission0.eid_from=X.cw_eid AND rel_read_permission0.eid_to=Y.cw_eid)
+SELECT _X.cw_eid, _Y.cw_eid
+FROM cw_CWEType AS _X, cw_RQLExpression AS _Y
+WHERE _X.cw_name=CWGroup AND _Y.cw_eid IN(1, 2, 3) AND NOT EXISTS(SELECT 1 FROM read_permission_relation AS rel_read_permission0 WHERE rel_read_permission0.eid_from=_X.cw_eid AND rel_read_permission0.eid_to=_Y.cw_eid)
 UNION ALL
-SELECT X.cw_eid, Y.cw_eid
-FROM cw_CWGroup AS Y, cw_CWRType AS X
-WHERE X.cw_name=CWGroup AND Y.cw_eid IN(1, 2, 3) AND NOT EXISTS(SELECT 1 FROM read_permission_relation AS rel_read_permission0 WHERE rel_read_permission0.eid_from=X.cw_eid AND rel_read_permission0.eid_to=Y.cw_eid)
+SELECT _X.cw_eid, _Y.cw_eid
+FROM cw_CWGroup AS _Y, cw_CWRType AS _X
+WHERE _X.cw_name=CWGroup AND _Y.cw_eid IN(1, 2, 3) AND NOT EXISTS(SELECT 1 FROM read_permission_relation AS rel_read_permission0 WHERE rel_read_permission0.eid_from=_X.cw_eid AND rel_read_permission0.eid_to=_Y.cw_eid)
 UNION ALL
-SELECT X.cw_eid, Y.cw_eid
-FROM cw_CWRType AS X, cw_RQLExpression AS Y
-WHERE X.cw_name=CWGroup AND Y.cw_eid IN(1, 2, 3) AND NOT EXISTS(SELECT 1 FROM read_permission_relation AS rel_read_permission0 WHERE rel_read_permission0.eid_from=X.cw_eid AND rel_read_permission0.eid_to=Y.cw_eid)'''),
+SELECT _X.cw_eid, _Y.cw_eid
+FROM cw_CWRType AS _X, cw_RQLExpression AS _Y
+WHERE _X.cw_name=CWGroup AND _Y.cw_eid IN(1, 2, 3) AND NOT EXISTS(SELECT 1 FROM read_permission_relation AS rel_read_permission0 WHERE rel_read_permission0.eid_from=_X.cw_eid AND rel_read_permission0.eid_to=_Y.cw_eid)'''),
 
     ('Any MAX(X)+MIN(X), N GROUPBY N WHERE X name N, X is IN (Basket, Folder, Tag);',
-     '''SELECT (MAX(T1.C0) + MIN(T1.C0)), T1.C1 FROM (SELECT X.cw_eid AS C0, X.cw_name AS C1
-FROM cw_Basket AS X
+     '''SELECT (MAX(T1.C0) + MIN(T1.C0)), T1.C1 FROM (SELECT _X.cw_eid AS C0, _X.cw_name AS C1
+FROM cw_Basket AS _X
 UNION ALL
-SELECT X.cw_eid AS C0, X.cw_name AS C1
-FROM cw_Folder AS X
+SELECT _X.cw_eid AS C0, _X.cw_name AS C1
+FROM cw_Folder AS _X
 UNION ALL
-SELECT X.cw_eid AS C0, X.cw_name AS C1
-FROM cw_Tag AS X) AS T1
+SELECT _X.cw_eid AS C0, _X.cw_name AS C1
+FROM cw_Tag AS _X) AS T1
 GROUP BY T1.C1'''),
 
     ('Any MAX(X)+MIN(LENGTH(D)), N GROUPBY N ORDERBY 1, N, DF WHERE X data_name N, X data D, X data_format DF;',
-     '''SELECT (MAX(T1.C1) + MIN(LENGTH(T1.C0))), T1.C2 FROM (SELECT X.cw_data AS C0, X.cw_eid AS C1, X.cw_data_name AS C2, X.cw_data_format AS C3
-FROM cw_File AS X
+     '''SELECT (MAX(T1.C1) + MIN(LENGTH(T1.C0))), T1.C2 FROM (SELECT _X.cw_data AS C0, _X.cw_eid AS C1, _X.cw_data_name AS C2, _X.cw_data_format AS C3
+FROM cw_File AS _X
 UNION ALL
-SELECT X.cw_data AS C0, X.cw_eid AS C1, X.cw_data_name AS C2, X.cw_data_format AS C3
-FROM cw_Image AS X) AS T1
-GROUP BY T1.C2
+SELECT _X.cw_data AS C0, _X.cw_eid AS C1, _X.cw_data_name AS C2, _X.cw_data_format AS C3
+FROM cw_Image AS _X) AS T1
+GROUP BY T1.C2,T1.C3
 ORDER BY 1,2,T1.C3'''),
 
     ('DISTINCT Any S ORDERBY R WHERE A is Affaire, A sujet S, A ref R',
-     '''SELECT T1.C0 FROM (SELECT DISTINCT A.cw_sujet AS C0, A.cw_ref AS C1
-FROM cw_Affaire AS A
+     '''SELECT T1.C0 FROM (SELECT DISTINCT _A.cw_sujet AS C0, _A.cw_ref AS C1
+FROM cw_Affaire AS _A
 ORDER BY 2) AS T1'''),
 
     ('DISTINCT Any MAX(X)+MIN(LENGTH(D)), N GROUPBY N ORDERBY 2, DF WHERE X data_name N, X data D, X data_format DF;',
-     '''SELECT T1.C0,T1.C1 FROM (SELECT DISTINCT (MAX(T1.C1) + MIN(LENGTH(T1.C0))) AS C0, T1.C2 AS C1, T1.C3 AS C2 FROM (SELECT DISTINCT X.cw_data AS C0, X.cw_eid AS C1, X.cw_data_name AS C2, X.cw_data_format AS C3
-FROM cw_File AS X
+     '''SELECT T1.C0,T1.C1 FROM (SELECT DISTINCT (MAX(T1.C1) + MIN(LENGTH(T1.C0))) AS C0, T1.C2 AS C1, T1.C3 AS C2 FROM (SELECT DISTINCT _X.cw_data AS C0, _X.cw_eid AS C1, _X.cw_data_name AS C2, _X.cw_data_format AS C3
+FROM cw_File AS _X
 UNION
-SELECT DISTINCT X.cw_data AS C0, X.cw_eid AS C1, X.cw_data_name AS C2, X.cw_data_format AS C3
-FROM cw_Image AS X) AS T1
+SELECT DISTINCT _X.cw_data AS C0, _X.cw_eid AS C1, _X.cw_data_name AS C2, _X.cw_data_format AS C3
+FROM cw_Image AS _X) AS T1
 GROUP BY T1.C2,T1.C3
 ORDER BY 2,3) AS T1
 '''),
 
     # ambiguity in EXISTS() -> should union the sub-query
     ('Any T WHERE T is Tag, NOT T name in ("t1", "t2"), EXISTS(T tags X, X is IN (CWUser, CWGroup))',
-     '''SELECT T.cw_eid
-FROM cw_Tag AS T
-WHERE NOT (T.cw_name IN(t1, t2)) AND EXISTS(SELECT 1 FROM tags_relation AS rel_tags0, cw_CWGroup AS X WHERE rel_tags0.eid_from=T.cw_eid AND rel_tags0.eid_to=X.cw_eid UNION SELECT 1 FROM tags_relation AS rel_tags1, cw_CWUser AS X WHERE rel_tags1.eid_from=T.cw_eid AND rel_tags1.eid_to=X.cw_eid)'''),
+     '''SELECT _T.cw_eid
+FROM cw_Tag AS _T
+WHERE NOT (_T.cw_name IN(t1, t2)) AND EXISTS(SELECT 1 FROM tags_relation AS rel_tags0, cw_CWGroup AS _X WHERE rel_tags0.eid_from=_T.cw_eid AND rel_tags0.eid_to=_X.cw_eid UNION SELECT 1 FROM tags_relation AS rel_tags1, cw_CWUser AS _X WHERE rel_tags1.eid_from=_T.cw_eid AND rel_tags1.eid_to=_X.cw_eid)'''),
 
     # must not use a relation in EXISTS scope to inline a variable
     ('Any U WHERE U eid IN (1,2), EXISTS(X owned_by U)',
-     '''SELECT U.cw_eid
-FROM cw_CWUser AS U
-WHERE U.cw_eid IN(1, 2) AND EXISTS(SELECT 1 FROM owned_by_relation AS rel_owned_by0 WHERE rel_owned_by0.eid_to=U.cw_eid)'''),
+     '''SELECT _U.cw_eid
+FROM cw_CWUser AS _U
+WHERE _U.cw_eid IN(1, 2) AND EXISTS(SELECT 1 FROM owned_by_relation AS rel_owned_by0 WHERE rel_owned_by0.eid_to=_U.cw_eid)'''),
 
     ('Any U WHERE EXISTS(U eid IN (1,2), X owned_by U)',
-     '''SELECT U.cw_eid
-FROM cw_CWUser AS U
-WHERE EXISTS(SELECT 1 FROM owned_by_relation AS rel_owned_by0 WHERE U.cw_eid IN(1, 2) AND rel_owned_by0.eid_to=U.cw_eid)'''),
+     '''SELECT _U.cw_eid
+FROM cw_CWUser AS _U
+WHERE EXISTS(SELECT 1 FROM owned_by_relation AS rel_owned_by0 WHERE _U.cw_eid IN(1, 2) AND rel_owned_by0.eid_to=_U.cw_eid)'''),
 
     ('Any COUNT(U) WHERE EXISTS (P owned_by U, P is IN (Note, Affaire))',
-     '''SELECT COUNT(U.cw_eid)
-FROM cw_CWUser AS U
-WHERE EXISTS(SELECT 1 FROM owned_by_relation AS rel_owned_by0, cw_Affaire AS P WHERE rel_owned_by0.eid_from=P.cw_eid AND rel_owned_by0.eid_to=U.cw_eid UNION SELECT 1 FROM owned_by_relation AS rel_owned_by1, cw_Note AS P WHERE rel_owned_by1.eid_from=P.cw_eid AND rel_owned_by1.eid_to=U.cw_eid)'''),
+     '''SELECT COUNT(_U.cw_eid)
+FROM cw_CWUser AS _U
+WHERE EXISTS(SELECT 1 FROM owned_by_relation AS rel_owned_by0, cw_Affaire AS _P WHERE rel_owned_by0.eid_from=_P.cw_eid AND rel_owned_by0.eid_to=_U.cw_eid UNION SELECT 1 FROM owned_by_relation AS rel_owned_by1, cw_Note AS _P WHERE rel_owned_by1.eid_from=_P.cw_eid AND rel_owned_by1.eid_to=_U.cw_eid)'''),
 
     ('Any MAX(X)',
-     '''SELECT MAX(X.eid)
-FROM entities AS X'''),
+     '''SELECT MAX(_X.eid)
+FROM entities AS _X'''),
 
     ('Any MAX(X) WHERE X is Note',
-     '''SELECT MAX(X.cw_eid)
-FROM cw_Note AS X'''),
+     '''SELECT MAX(_X.cw_eid)
+FROM cw_Note AS _X'''),
 
     ('Any X WHERE X eid > 12',
-     '''SELECT X.eid
-FROM entities AS X
-WHERE X.eid>12'''),
+     '''SELECT _X.eid
+FROM entities AS _X
+WHERE _X.eid>12'''),
 
     ('Any X WHERE X eid > 12, X is Note',
-     """SELECT X.eid
-FROM entities AS X
-WHERE X.type='Note' AND X.eid>12"""),
+     """SELECT _X.eid
+FROM entities AS _X
+WHERE _X.type='Note' AND _X.eid>12"""),
 
     ('Any X, T WHERE X eid > 12, X title T, X is IN (Bookmark, Card)',
-     """SELECT X.cw_eid, X.cw_title
-FROM cw_Bookmark AS X
-WHERE X.cw_eid>12
+     """SELECT _X.cw_eid, _X.cw_title
+FROM cw_Bookmark AS _X
+WHERE _X.cw_eid>12
 UNION ALL
-SELECT X.cw_eid, X.cw_title
-FROM cw_Card AS X
-WHERE X.cw_eid>12"""),
+SELECT _X.cw_eid, _X.cw_title
+FROM cw_Card AS _X
+WHERE _X.cw_eid>12"""),
 
     ('Any X',
-     '''SELECT X.eid
-FROM entities AS X'''),
+     '''SELECT _X.eid
+FROM entities AS _X'''),
 
     ('Any X GROUPBY X WHERE X eid 12',
      '''SELECT 12'''),
 
     ('Any X GROUPBY X ORDERBY Y WHERE X eid 12, X login Y',
-     '''SELECT X.cw_eid
-FROM cw_CWUser AS X
-WHERE X.cw_eid=12
-GROUP BY X.cw_eid
-ORDER BY X.cw_login'''),
+     '''SELECT _X.cw_eid
+FROM cw_CWUser AS _X
+WHERE _X.cw_eid=12
+GROUP BY _X.cw_eid,_X.cw_login
+ORDER BY _X.cw_login'''),
 
     ('Any U,COUNT(X) GROUPBY U WHERE U eid 12, X owned_by U HAVING COUNT(X) > 10',
      '''SELECT rel_owned_by0.eid_to, COUNT(rel_owned_by0.eid_from)
@@ -536,36 +540,36 @@
 HAVING COUNT(rel_owned_by0.eid_from)>10'''),
 
     ('DISTINCT Any X ORDERBY stockproc(X) WHERE U login X',
-     '''SELECT T1.C0 FROM (SELECT DISTINCT U.cw_login AS C0, STOCKPROC(U.cw_login) AS C1
-FROM cw_CWUser AS U
+     '''SELECT T1.C0 FROM (SELECT DISTINCT _U.cw_login AS C0, STOCKPROC(_U.cw_login) AS C1
+FROM cw_CWUser AS _U
 ORDER BY 2) AS T1'''),
 
     ('DISTINCT Any X ORDERBY Y WHERE B bookmarked_by X, X login Y',
-     '''SELECT T1.C0 FROM (SELECT DISTINCT X.cw_eid AS C0, X.cw_login AS C1
-FROM bookmarked_by_relation AS rel_bookmarked_by0, cw_CWUser AS X
-WHERE rel_bookmarked_by0.eid_to=X.cw_eid
+     '''SELECT T1.C0 FROM (SELECT DISTINCT _X.cw_eid AS C0, _X.cw_login AS C1
+FROM bookmarked_by_relation AS rel_bookmarked_by0, cw_CWUser AS _X
+WHERE rel_bookmarked_by0.eid_to=_X.cw_eid
 ORDER BY 2) AS T1'''),
 
     ('DISTINCT Any X ORDERBY SN WHERE X in_state S, S name SN',
-     '''SELECT T1.C0 FROM (SELECT DISTINCT X.cw_eid AS C0, S.cw_name AS C1
-FROM cw_Affaire AS X, cw_State AS S
-WHERE X.cw_in_state=S.cw_eid
+     '''SELECT T1.C0 FROM (SELECT DISTINCT _X.cw_eid AS C0, _S.cw_name AS C1
+FROM cw_Affaire AS _X, cw_State AS _S
+WHERE _X.cw_in_state=_S.cw_eid
 UNION
-SELECT DISTINCT X.cw_eid AS C0, S.cw_name AS C1
-FROM cw_CWUser AS X, cw_State AS S
-WHERE X.cw_in_state=S.cw_eid
+SELECT DISTINCT _X.cw_eid AS C0, _S.cw_name AS C1
+FROM cw_CWUser AS _X, cw_State AS _S
+WHERE _X.cw_in_state=_S.cw_eid
 UNION
-SELECT DISTINCT X.cw_eid AS C0, S.cw_name AS C1
-FROM cw_Note AS X, cw_State AS S
-WHERE X.cw_in_state=S.cw_eid
+SELECT DISTINCT _X.cw_eid AS C0, _S.cw_name AS C1
+FROM cw_Note AS _X, cw_State AS _S
+WHERE _X.cw_in_state=_S.cw_eid
 ORDER BY 2) AS T1'''),
 
     ('Any O,AA,AB,AC ORDERBY AC DESC '
      'WHERE NOT S use_email O, S eid 1, O is EmailAddress, O address AA, O alias AB, O modification_date AC, '
      'EXISTS(A use_email O, EXISTS(A identity B, NOT B in_group D, D name "guests", D is CWGroup), A is CWUser), B eid 2',
-     '''SELECT O.cw_eid, O.cw_address, O.cw_alias, O.cw_modification_date
-FROM cw_EmailAddress AS O
-WHERE NOT EXISTS(SELECT 1 FROM use_email_relation AS rel_use_email0 WHERE rel_use_email0.eid_from=1 AND rel_use_email0.eid_to=O.cw_eid) AND EXISTS(SELECT 1 FROM use_email_relation AS rel_use_email1 WHERE rel_use_email1.eid_to=O.cw_eid AND EXISTS(SELECT 1 FROM cw_CWGroup AS D WHERE rel_use_email1.eid_from=2 AND NOT EXISTS(SELECT 1 FROM in_group_relation AS rel_in_group2 WHERE rel_in_group2.eid_from=2 AND rel_in_group2.eid_to=D.cw_eid) AND D.cw_name=guests))
+     '''SELECT _O.cw_eid, _O.cw_address, _O.cw_alias, _O.cw_modification_date
+FROM cw_EmailAddress AS _O
+WHERE NOT EXISTS(SELECT 1 FROM use_email_relation AS rel_use_email0 WHERE rel_use_email0.eid_from=1 AND rel_use_email0.eid_to=_O.cw_eid) AND EXISTS(SELECT 1 FROM use_email_relation AS rel_use_email1 WHERE rel_use_email1.eid_to=_O.cw_eid AND EXISTS(SELECT 1 FROM cw_CWGroup AS _D WHERE rel_use_email1.eid_from=2 AND NOT EXISTS(SELECT 1 FROM in_group_relation AS rel_in_group2 WHERE rel_in_group2.eid_from=2 AND rel_in_group2.eid_to=_D.cw_eid) AND _D.cw_name=guests))
 ORDER BY 4 DESC'''),
 
 
@@ -573,59 +577,82 @@
      '''SELECT 0'''),
 
     ("Any X WHERE X eid 0, X eid 0, X test TRUE",
-     '''SELECT X.cw_eid
-FROM cw_Personne AS X
-WHERE X.cw_eid=0 AND X.cw_eid=0 AND X.cw_test='''),
+     '''SELECT _X.cw_eid
+FROM cw_Personne AS _X
+WHERE _X.cw_eid=0 AND _X.cw_eid=0 AND _X.cw_test=TRUE'''),
+
+    ("Any X,GROUP_CONCAT(TN) GROUPBY X ORDERBY XN WHERE T tags X, X name XN, T name TN, X is CWGroup",
+     '''SELECT _X.cw_eid, GROUP_CONCAT(_T.cw_name)
+FROM cw_CWGroup AS _X, cw_Tag AS _T, tags_relation AS rel_tags0
+WHERE rel_tags0.eid_from=_T.cw_eid AND rel_tags0.eid_to=_X.cw_eid
+GROUP BY _X.cw_eid,_X.cw_name
+ORDER BY _X.cw_name'''),
+
+    ("Any X,GROUP_CONCAT(TN) GROUPBY X ORDERBY XN WHERE T tags X, X name XN, T name TN",
+     '''SELECT T1.C0, GROUP_CONCAT(T1.C1) FROM (SELECT _X.cw_eid AS C0, _T.cw_name AS C1, _X.cw_name AS C2
+FROM cw_CWGroup AS _X, cw_Tag AS _T, tags_relation AS rel_tags0
+WHERE rel_tags0.eid_from=_T.cw_eid AND rel_tags0.eid_to=_X.cw_eid
+UNION ALL
+SELECT _X.cw_eid AS C0, _T.cw_name AS C1, _X.cw_name AS C2
+FROM cw_State AS _X, cw_Tag AS _T, tags_relation AS rel_tags0
+WHERE rel_tags0.eid_from=_T.cw_eid AND rel_tags0.eid_to=_X.cw_eid
+UNION ALL
+SELECT _X.cw_eid AS C0, _T.cw_name AS C1, _X.cw_name AS C2
+FROM cw_Tag AS _T, cw_Tag AS _X, tags_relation AS rel_tags0
+WHERE rel_tags0.eid_from=_T.cw_eid AND rel_tags0.eid_to=_X.cw_eid) AS T1
+GROUP BY T1.C0,T1.C2
+ORDER BY T1.C2'''),
+
     ]
 
 MULTIPLE_SEL = [
     ("DISTINCT Any X,Y where P is Personne, P nom X , P prenom Y;",
-     '''SELECT DISTINCT P.cw_nom, P.cw_prenom
-FROM cw_Personne AS P'''),
+     '''SELECT DISTINCT _P.cw_nom, _P.cw_prenom
+FROM cw_Personne AS _P'''),
     ("Any X,Y where P is Personne, P nom X , P prenom Y, not P nom NULL;",
-     '''SELECT P.cw_nom, P.cw_prenom
-FROM cw_Personne AS P
-WHERE NOT (P.cw_nom IS NULL)'''),
+     '''SELECT _P.cw_nom, _P.cw_prenom
+FROM cw_Personne AS _P
+WHERE NOT (_P.cw_nom IS NULL)'''),
     ("Personne X,Y where X nom NX, Y nom NX, X eid XE, not Y eid XE",
-     '''SELECT X.cw_eid, Y.cw_eid
-FROM cw_Personne AS X, cw_Personne AS Y
-WHERE Y.cw_nom=X.cw_nom AND NOT (Y.cw_eid=X.cw_eid)''')
+     '''SELECT _X.cw_eid, _Y.cw_eid
+FROM cw_Personne AS _X, cw_Personne AS _Y
+WHERE _Y.cw_nom=_X.cw_nom AND NOT (_Y.cw_eid=_X.cw_eid)''')
     ]
 
 NEGATIONS = [
     ("Personne X WHERE NOT X evaluee Y;",
-     '''SELECT X.cw_eid
-FROM cw_Personne AS X
-WHERE NOT EXISTS(SELECT 1 FROM evaluee_relation AS rel_evaluee0 WHERE rel_evaluee0.eid_from=X.cw_eid)'''),
+     '''SELECT _X.cw_eid
+FROM cw_Personne AS _X
+WHERE NOT EXISTS(SELECT 1 FROM evaluee_relation AS rel_evaluee0 WHERE rel_evaluee0.eid_from=_X.cw_eid)'''),
 
     ("Note N WHERE NOT X evaluee N, X eid 0",
-     '''SELECT N.cw_eid
-FROM cw_Note AS N
-WHERE NOT EXISTS(SELECT 1 FROM evaluee_relation AS rel_evaluee0 WHERE rel_evaluee0.eid_from=0 AND rel_evaluee0.eid_to=N.cw_eid)'''),
+     '''SELECT _N.cw_eid
+FROM cw_Note AS _N
+WHERE NOT EXISTS(SELECT 1 FROM evaluee_relation AS rel_evaluee0 WHERE rel_evaluee0.eid_from=0 AND rel_evaluee0.eid_to=_N.cw_eid)'''),
 
     ('Any X WHERE NOT X travaille S, X is Personne',
-     '''SELECT X.cw_eid
-FROM cw_Personne AS X
-WHERE NOT EXISTS(SELECT 1 FROM travaille_relation AS rel_travaille0 WHERE rel_travaille0.eid_from=X.cw_eid)'''),
+     '''SELECT _X.cw_eid
+FROM cw_Personne AS _X
+WHERE NOT EXISTS(SELECT 1 FROM travaille_relation AS rel_travaille0 WHERE rel_travaille0.eid_from=_X.cw_eid)'''),
 
     ("Personne P where not P datenaiss TODAY",
-     '''SELECT P.cw_eid
-FROM cw_Personne AS P
-WHERE NOT (DATE(P.cw_datenaiss)=CURRENT_DATE)'''),
+     '''SELECT _P.cw_eid
+FROM cw_Personne AS _P
+WHERE NOT (DATE(_P.cw_datenaiss)=CURRENT_DATE)'''),
 
     ("Personne P where NOT P concerne A",
-     '''SELECT P.cw_eid
-FROM cw_Personne AS P
-WHERE NOT EXISTS(SELECT 1 FROM concerne_relation AS rel_concerne0 WHERE rel_concerne0.eid_from=P.cw_eid)'''),
+     '''SELECT _P.cw_eid
+FROM cw_Personne AS _P
+WHERE NOT EXISTS(SELECT 1 FROM concerne_relation AS rel_concerne0 WHERE rel_concerne0.eid_from=_P.cw_eid)'''),
 
     ("Affaire A where not P concerne A",
-     '''SELECT A.cw_eid
-FROM cw_Affaire AS A
-WHERE NOT EXISTS(SELECT 1 FROM concerne_relation AS rel_concerne0 WHERE rel_concerne0.eid_to=A.cw_eid)'''),
+     '''SELECT _A.cw_eid
+FROM cw_Affaire AS _A
+WHERE NOT EXISTS(SELECT 1 FROM concerne_relation AS rel_concerne0 WHERE rel_concerne0.eid_to=_A.cw_eid)'''),
     ("Personne P where not P concerne A, A sujet ~= 'TEST%'",
-     '''SELECT P.cw_eid
-FROM cw_Affaire AS A, cw_Personne AS P
-WHERE NOT EXISTS(SELECT 1 FROM concerne_relation AS rel_concerne0 WHERE rel_concerne0.eid_from=P.cw_eid AND rel_concerne0.eid_to=A.cw_eid) AND A.cw_sujet ILIKE TEST%'''),
+     '''SELECT _P.cw_eid
+FROM cw_Affaire AS _A, cw_Personne AS _P
+WHERE NOT EXISTS(SELECT 1 FROM concerne_relation AS rel_concerne0 WHERE rel_concerne0.eid_from=_P.cw_eid AND rel_concerne0.eid_to=_A.cw_eid) AND _A.cw_sujet ILIKE TEST%'''),
 
     ('Any S WHERE NOT T eid 28258, T tags S',
      '''SELECT rel_tags0.eid_to
@@ -633,17 +660,17 @@
 WHERE NOT (rel_tags0.eid_from=28258)'''),
 
     ('Any S WHERE T is Tag, T name TN, NOT T eid 28258, T tags S, S name SN',
-     '''SELECT S.cw_eid
-FROM cw_CWGroup AS S, cw_Tag AS T, tags_relation AS rel_tags0
-WHERE NOT (T.cw_eid=28258) AND rel_tags0.eid_from=T.cw_eid AND rel_tags0.eid_to=S.cw_eid
+     '''SELECT _S.cw_eid
+FROM cw_CWGroup AS _S, cw_Tag AS _T, tags_relation AS rel_tags0
+WHERE NOT (_T.cw_eid=28258) AND rel_tags0.eid_from=_T.cw_eid AND rel_tags0.eid_to=_S.cw_eid
 UNION ALL
-SELECT S.cw_eid
-FROM cw_State AS S, cw_Tag AS T, tags_relation AS rel_tags0
-WHERE NOT (T.cw_eid=28258) AND rel_tags0.eid_from=T.cw_eid AND rel_tags0.eid_to=S.cw_eid
+SELECT _S.cw_eid
+FROM cw_State AS _S, cw_Tag AS _T, tags_relation AS rel_tags0
+WHERE NOT (_T.cw_eid=28258) AND rel_tags0.eid_from=_T.cw_eid AND rel_tags0.eid_to=_S.cw_eid
 UNION ALL
-SELECT S.cw_eid
-FROM cw_Tag AS S, cw_Tag AS T, tags_relation AS rel_tags0
-WHERE NOT (T.cw_eid=28258) AND rel_tags0.eid_from=T.cw_eid AND rel_tags0.eid_to=S.cw_eid'''),
+SELECT _S.cw_eid
+FROM cw_Tag AS _S, cw_Tag AS _T, tags_relation AS rel_tags0
+WHERE NOT (_T.cw_eid=28258) AND rel_tags0.eid_from=_T.cw_eid AND rel_tags0.eid_to=_S.cw_eid'''),
 
     ('Any X,Y WHERE X created_by Y, X eid 5, NOT Y eid 6',
      '''SELECT 5, rel_created_by0.eid_to
@@ -651,406 +678,406 @@
 WHERE rel_created_by0.eid_from=5 AND NOT (rel_created_by0.eid_to=6)'''),
 
     ('Note X WHERE NOT Y evaluee X',
-     '''SELECT X.cw_eid
-FROM cw_Note AS X
-WHERE NOT EXISTS(SELECT 1 FROM evaluee_relation AS rel_evaluee0 WHERE rel_evaluee0.eid_to=X.cw_eid)'''),
+     '''SELECT _X.cw_eid
+FROM cw_Note AS _X
+WHERE NOT EXISTS(SELECT 1 FROM evaluee_relation AS rel_evaluee0 WHERE rel_evaluee0.eid_to=_X.cw_eid)'''),
 
     ('Any Y WHERE NOT Y evaluee X',
-     '''SELECT Y.cw_eid
-FROM cw_CWUser AS Y
-WHERE NOT EXISTS(SELECT 1 FROM evaluee_relation AS rel_evaluee0 WHERE rel_evaluee0.eid_from=Y.cw_eid)
+     '''SELECT _Y.cw_eid
+FROM cw_CWUser AS _Y
+WHERE NOT EXISTS(SELECT 1 FROM evaluee_relation AS rel_evaluee0 WHERE rel_evaluee0.eid_from=_Y.cw_eid)
 UNION ALL
-SELECT Y.cw_eid
-FROM cw_Division AS Y
-WHERE NOT EXISTS(SELECT 1 FROM evaluee_relation AS rel_evaluee0 WHERE rel_evaluee0.eid_from=Y.cw_eid)
+SELECT _Y.cw_eid
+FROM cw_Division AS _Y
+WHERE NOT EXISTS(SELECT 1 FROM evaluee_relation AS rel_evaluee0 WHERE rel_evaluee0.eid_from=_Y.cw_eid)
 UNION ALL
-SELECT Y.cw_eid
-FROM cw_Personne AS Y
-WHERE NOT EXISTS(SELECT 1 FROM evaluee_relation AS rel_evaluee0 WHERE rel_evaluee0.eid_from=Y.cw_eid)
+SELECT _Y.cw_eid
+FROM cw_Personne AS _Y
+WHERE NOT EXISTS(SELECT 1 FROM evaluee_relation AS rel_evaluee0 WHERE rel_evaluee0.eid_from=_Y.cw_eid)
 UNION ALL
-SELECT Y.cw_eid
-FROM cw_Societe AS Y
-WHERE NOT EXISTS(SELECT 1 FROM evaluee_relation AS rel_evaluee0 WHERE rel_evaluee0.eid_from=Y.cw_eid)
+SELECT _Y.cw_eid
+FROM cw_Societe AS _Y
+WHERE NOT EXISTS(SELECT 1 FROM evaluee_relation AS rel_evaluee0 WHERE rel_evaluee0.eid_from=_Y.cw_eid)
 UNION ALL
-SELECT Y.cw_eid
-FROM cw_SubDivision AS Y
-WHERE NOT EXISTS(SELECT 1 FROM evaluee_relation AS rel_evaluee0 WHERE rel_evaluee0.eid_from=Y.cw_eid)'''),
+SELECT _Y.cw_eid
+FROM cw_SubDivision AS _Y
+WHERE NOT EXISTS(SELECT 1 FROM evaluee_relation AS rel_evaluee0 WHERE rel_evaluee0.eid_from=_Y.cw_eid)'''),
 
     ('Any X WHERE NOT Y evaluee X, Y is CWUser',
-     '''SELECT X.cw_eid
-FROM cw_Note AS X
-WHERE NOT EXISTS(SELECT 1 FROM evaluee_relation AS rel_evaluee0,cw_CWUser AS Y WHERE rel_evaluee0.eid_from=Y.cw_eid AND rel_evaluee0.eid_to=X.cw_eid)'''),
+     '''SELECT _X.cw_eid
+FROM cw_Note AS _X
+WHERE NOT EXISTS(SELECT 1 FROM evaluee_relation AS rel_evaluee0,cw_CWUser AS _Y WHERE rel_evaluee0.eid_from=_Y.cw_eid AND rel_evaluee0.eid_to=_X.cw_eid)'''),
 
     ('Any X,RT WHERE X relation_type RT, NOT X is CWAttribute',
-     '''SELECT X.cw_eid, X.cw_relation_type
-FROM cw_CWRelation AS X
-WHERE X.cw_relation_type IS NOT NULL'''),
+     '''SELECT _X.cw_eid, _X.cw_relation_type
+FROM cw_CWRelation AS _X
+WHERE _X.cw_relation_type IS NOT NULL'''),
 
     ('Any K,V WHERE P is CWProperty, P pkey K, P value V, NOT P for_user U',
-     '''SELECT P.cw_pkey, P.cw_value
-FROM cw_CWProperty AS P
-WHERE P.cw_for_user IS NULL'''),
+     '''SELECT _P.cw_pkey, _P.cw_value
+FROM cw_CWProperty AS _P
+WHERE _P.cw_for_user IS NULL'''),
 
     ('Any S WHERE NOT X in_state S, X is IN(Affaire, CWUser)',
-     '''SELECT S.cw_eid
-FROM cw_State AS S
-WHERE NOT EXISTS(SELECT 1 FROM cw_Affaire AS X WHERE X.cw_in_state=S.cw_eid)
+     '''SELECT _S.cw_eid
+FROM cw_State AS _S
+WHERE NOT EXISTS(SELECT 1 FROM cw_Affaire AS _X WHERE _X.cw_in_state=_S.cw_eid)
 INTERSECT
-SELECT S.cw_eid
-FROM cw_State AS S
-WHERE NOT EXISTS(SELECT 1 FROM cw_CWUser AS X WHERE X.cw_in_state=S.cw_eid)'''),
+SELECT _S.cw_eid
+FROM cw_State AS _S
+WHERE NOT EXISTS(SELECT 1 FROM cw_CWUser AS _X WHERE _X.cw_in_state=_S.cw_eid)'''),
 
     ('Any S WHERE NOT(X in_state S, S name "somename"), X is CWUser',
-     '''SELECT S.cw_eid
-FROM cw_State AS S
-WHERE NOT EXISTS(SELECT 1 FROM cw_CWUser AS X WHERE X.cw_in_state=S.cw_eid AND S.cw_name=somename)'''),
+     '''SELECT _S.cw_eid
+FROM cw_State AS _S
+WHERE NOT EXISTS(SELECT 1 FROM cw_CWUser AS _X WHERE _X.cw_in_state=_S.cw_eid AND _S.cw_name=somename)'''),
    
 # XXXFIXME fail
 #         ('Any X,RT WHERE X relation_type RT?, NOT X is CWAttribute',
-#      '''SELECT X.cw_eid, X.cw_relation_type
-# FROM cw_CWRelation AS X'''),
+#      '''SELECT _X.cw_eid, _X.cw_relation_type
+# FROM cw_CWRelation AS _X'''),
 ]
 
 OUTER_JOIN = [
     ('Any X,S WHERE X travaille S?',
-     '''SELECT X.cw_eid, rel_travaille0.eid_to
-FROM cw_Personne AS X LEFT OUTER JOIN travaille_relation AS rel_travaille0 ON (rel_travaille0.eid_from=X.cw_eid)'''
+     '''SELECT _X.cw_eid, rel_travaille0.eid_to
+FROM cw_Personne AS _X LEFT OUTER JOIN travaille_relation AS rel_travaille0 ON (rel_travaille0.eid_from=_X.cw_eid)'''
     ),
     ('Any S,X WHERE X? travaille S, S is Societe',
-     '''SELECT S.cw_eid, rel_travaille0.eid_from
-FROM cw_Societe AS S LEFT OUTER JOIN travaille_relation AS rel_travaille0 ON (rel_travaille0.eid_to=S.cw_eid)'''
+     '''SELECT _S.cw_eid, rel_travaille0.eid_from
+FROM cw_Societe AS _S LEFT OUTER JOIN travaille_relation AS rel_travaille0 ON (rel_travaille0.eid_to=_S.cw_eid)'''
     ),
 
     ('Any N,A WHERE N inline1 A?',
-     '''SELECT N.cw_eid, N.cw_inline1
-FROM cw_Note AS N'''),
+     '''SELECT _N.cw_eid, _N.cw_inline1
+FROM cw_Note AS _N'''),
 
     ('Any SN WHERE X from_state S?, S name SN',
-     '''SELECT S.cw_name
-FROM cw_TrInfo AS X LEFT OUTER JOIN cw_State AS S ON (X.cw_from_state=S.cw_eid)'''
+     '''SELECT _S.cw_name
+FROM cw_TrInfo AS _X LEFT OUTER JOIN cw_State AS _S ON (_X.cw_from_state=_S.cw_eid)'''
     ),
 
     ('Any A,N WHERE N? inline1 A',
-     '''SELECT A.cw_eid, N.cw_eid
-FROM cw_Affaire AS A LEFT OUTER JOIN cw_Note AS N ON (N.cw_inline1=A.cw_eid)'''
+     '''SELECT _A.cw_eid, _N.cw_eid
+FROM cw_Affaire AS _A LEFT OUTER JOIN cw_Note AS _N ON (_N.cw_inline1=_A.cw_eid)'''
     ),
 
     ('Any A,B,C,D,E,F,G WHERE A eid 12,A creation_date B,A modification_date C,A comment D,A from_state E?,A to_state F?,A wf_info_for G?',
-    '''SELECT A.cw_eid, A.cw_creation_date, A.cw_modification_date, A.cw_comment, A.cw_from_state, A.cw_to_state, A.cw_wf_info_for
-FROM cw_TrInfo AS A
-WHERE A.cw_eid=12'''),
+    '''SELECT _A.cw_eid, _A.cw_creation_date, _A.cw_modification_date, _A.cw_comment, _A.cw_from_state, _A.cw_to_state, _A.cw_wf_info_for
+FROM cw_TrInfo AS _A
+WHERE _A.cw_eid=12'''),
 
     ('Any FS,TS,C,D,U ORDERBY D DESC WHERE WF wf_info_for X,WF from_state FS?, WF to_state TS, WF comment C,WF creation_date D, WF owned_by U, X eid 1',
-     '''SELECT WF.cw_from_state, WF.cw_to_state, WF.cw_comment, WF.cw_creation_date, rel_owned_by0.eid_to
-FROM cw_TrInfo AS WF, owned_by_relation AS rel_owned_by0
-WHERE WF.cw_wf_info_for=1 AND WF.cw_to_state IS NOT NULL AND rel_owned_by0.eid_from=WF.cw_eid
+     '''SELECT _WF.cw_from_state, _WF.cw_to_state, _WF.cw_comment, _WF.cw_creation_date, rel_owned_by0.eid_to
+FROM cw_TrInfo AS _WF, owned_by_relation AS rel_owned_by0
+WHERE _WF.cw_wf_info_for=1 AND _WF.cw_to_state IS NOT NULL AND rel_owned_by0.eid_from=_WF.cw_eid
 ORDER BY 4 DESC'''),
 
     ('Any X WHERE X is Affaire, S is Societe, EXISTS(X owned_by U OR (X concerne S?, S owned_by U))',
-     '''SELECT X.cw_eid
-FROM cw_Affaire AS X
-WHERE EXISTS(SELECT 1 FROM owned_by_relation AS rel_owned_by0, cw_CWUser AS U, cw_Affaire AS A LEFT OUTER JOIN concerne_relation AS rel_concerne1 ON (rel_concerne1.eid_from=A.cw_eid) LEFT OUTER JOIN cw_Societe AS S ON (rel_concerne1.eid_to=S.cw_eid), owned_by_relation AS rel_owned_by2 WHERE ((rel_owned_by0.eid_from=A.cw_eid AND rel_owned_by0.eid_to=U.cw_eid) OR (rel_owned_by2.eid_from=S.cw_eid AND rel_owned_by2.eid_to=U.cw_eid)) AND X.cw_eid=A.cw_eid)'''),
+     '''SELECT _X.cw_eid
+FROM cw_Affaire AS _X
+WHERE EXISTS(SELECT 1 FROM owned_by_relation AS rel_owned_by0, cw_CWUser AS _U, cw_Affaire AS _A LEFT OUTER JOIN concerne_relation AS rel_concerne1 ON (rel_concerne1.eid_from=_A.cw_eid) LEFT OUTER JOIN cw_Societe AS _S ON (rel_concerne1.eid_to=_S.cw_eid), owned_by_relation AS rel_owned_by2 WHERE ((rel_owned_by0.eid_from=_A.cw_eid AND rel_owned_by0.eid_to=_U.cw_eid) OR (rel_owned_by2.eid_from=_S.cw_eid AND rel_owned_by2.eid_to=_U.cw_eid)) AND _X.cw_eid=_A.cw_eid)'''),
 
     ('Any C,M WHERE C travaille G?, G evaluee M?, G is Societe',
-     '''SELECT C.cw_eid, rel_evaluee1.eid_to
-FROM cw_Personne AS C LEFT OUTER JOIN travaille_relation AS rel_travaille0 ON (rel_travaille0.eid_from=C.cw_eid) LEFT OUTER JOIN cw_Societe AS G ON (rel_travaille0.eid_to=G.cw_eid) LEFT OUTER JOIN evaluee_relation AS rel_evaluee1 ON (rel_evaluee1.eid_from=G.cw_eid)'''
+     '''SELECT _C.cw_eid, rel_evaluee1.eid_to
+FROM cw_Personne AS _C LEFT OUTER JOIN travaille_relation AS rel_travaille0 ON (rel_travaille0.eid_from=_C.cw_eid) LEFT OUTER JOIN cw_Societe AS _G ON (rel_travaille0.eid_to=_G.cw_eid) LEFT OUTER JOIN evaluee_relation AS rel_evaluee1 ON (rel_evaluee1.eid_from=_G.cw_eid)'''
      ),
 
     ('Any A,C WHERE A documented_by C?, (C is NULL) OR (EXISTS(C require_permission F, '
      'F name "read", F require_group E, U in_group E)), U eid 1',
-     '''SELECT A.cw_eid, rel_documented_by0.eid_to
-FROM cw_Affaire AS A LEFT OUTER JOIN documented_by_relation AS rel_documented_by0 ON (rel_documented_by0.eid_from=A.cw_eid)
-WHERE ((rel_documented_by0.eid_to IS NULL) OR (EXISTS(SELECT 1 FROM require_permission_relation AS rel_require_permission1, cw_CWPermission AS F, require_group_relation AS rel_require_group2, in_group_relation AS rel_in_group3 WHERE rel_documented_by0.eid_to=rel_require_permission1.eid_from AND rel_require_permission1.eid_to=F.cw_eid AND F.cw_name=read AND rel_require_group2.eid_from=F.cw_eid AND rel_in_group3.eid_to=rel_require_group2.eid_to AND rel_in_group3.eid_from=1)))'''),
+     '''SELECT _A.cw_eid, rel_documented_by0.eid_to
+FROM cw_Affaire AS _A LEFT OUTER JOIN documented_by_relation AS rel_documented_by0 ON (rel_documented_by0.eid_from=_A.cw_eid)
+WHERE ((rel_documented_by0.eid_to IS NULL) OR (EXISTS(SELECT 1 FROM require_permission_relation AS rel_require_permission1, cw_CWPermission AS _F, require_group_relation AS rel_require_group2, in_group_relation AS rel_in_group3 WHERE rel_documented_by0.eid_to=rel_require_permission1.eid_from AND rel_require_permission1.eid_to=_F.cw_eid AND _F.cw_name=read AND rel_require_group2.eid_from=_F.cw_eid AND rel_in_group3.eid_to=rel_require_group2.eid_to AND rel_in_group3.eid_from=1)))'''),
 
     ("Any X WHERE X eid 12, P? connait X",
-     '''SELECT X.cw_eid
-FROM cw_Personne AS X LEFT OUTER JOIN connait_relation AS rel_connait0 ON (rel_connait0.eid_to=12)
-WHERE X.cw_eid=12'''
+     '''SELECT _X.cw_eid
+FROM cw_Personne AS _X LEFT OUTER JOIN connait_relation AS rel_connait0 ON (rel_connait0.eid_to=12)
+WHERE _X.cw_eid=12'''
     ),
 
     ('Any GN, TN ORDERBY GN WHERE T tags G?, T name TN, G name GN',
     '''
-SELECT _T0.C1, T.cw_name
-FROM cw_Tag AS T LEFT OUTER JOIN tags_relation AS rel_tags0 ON (rel_tags0.eid_from=T.cw_eid) LEFT OUTER JOIN (SELECT G.cw_eid AS C0, G.cw_name AS C1
-FROM cw_CWGroup AS G
+SELECT _T0.C1, _T.cw_name
+FROM cw_Tag AS _T LEFT OUTER JOIN tags_relation AS rel_tags0 ON (rel_tags0.eid_from=_T.cw_eid) LEFT OUTER JOIN (SELECT _G.cw_eid AS C0, _G.cw_name AS C1
+FROM cw_CWGroup AS _G
 UNION ALL
-SELECT G.cw_eid AS C0, G.cw_name AS C1
-FROM cw_State AS G
+SELECT _G.cw_eid AS C0, _G.cw_name AS C1
+FROM cw_State AS _G
 UNION ALL
-SELECT G.cw_eid AS C0, G.cw_name AS C1
-FROM cw_Tag AS G) AS _T0 ON (rel_tags0.eid_to=_T0.C0)
+SELECT _G.cw_eid AS C0, _G.cw_name AS C1
+FROM cw_Tag AS _G) AS _T0 ON (rel_tags0.eid_to=_T0.C0)
 ORDER BY 1'''),
 
 
     # optional variable with additional restriction
     ('Any T,G WHERE T tags G?, G name "hop", G is CWGroup',
-     '''SELECT T.cw_eid, G.cw_eid
-FROM cw_Tag AS T LEFT OUTER JOIN tags_relation AS rel_tags0 ON (rel_tags0.eid_from=T.cw_eid) LEFT OUTER JOIN cw_CWGroup AS G ON (rel_tags0.eid_to=G.cw_eid AND G.cw_name=hop)'''),
+     '''SELECT _T.cw_eid, _G.cw_eid
+FROM cw_Tag AS _T LEFT OUTER JOIN tags_relation AS rel_tags0 ON (rel_tags0.eid_from=_T.cw_eid) LEFT OUTER JOIN cw_CWGroup AS _G ON (rel_tags0.eid_to=_G.cw_eid AND _G.cw_name=hop)'''),
 
     # optional variable with additional invariant restriction
     ('Any T,G WHERE T tags G?, G eid 12',
-     '''SELECT T.cw_eid, rel_tags0.eid_to
-FROM cw_Tag AS T LEFT OUTER JOIN tags_relation AS rel_tags0 ON (rel_tags0.eid_from=T.cw_eid AND rel_tags0.eid_to=12)'''),
+     '''SELECT _T.cw_eid, rel_tags0.eid_to
+FROM cw_Tag AS _T LEFT OUTER JOIN tags_relation AS rel_tags0 ON (rel_tags0.eid_from=_T.cw_eid AND rel_tags0.eid_to=12)'''),
 
     # optional variable with additional restriction appearing before the relation
     ('Any T,G WHERE G name "hop", T tags G?, G is CWGroup',
-     '''SELECT T.cw_eid, G.cw_eid
-FROM cw_Tag AS T LEFT OUTER JOIN tags_relation AS rel_tags0 ON (rel_tags0.eid_from=T.cw_eid) LEFT OUTER JOIN cw_CWGroup AS G ON (rel_tags0.eid_to=G.cw_eid AND G.cw_name=hop)'''),
+     '''SELECT _T.cw_eid, _G.cw_eid
+FROM cw_Tag AS _T LEFT OUTER JOIN tags_relation AS rel_tags0 ON (rel_tags0.eid_from=_T.cw_eid) LEFT OUTER JOIN cw_CWGroup AS _G ON (rel_tags0.eid_to=_G.cw_eid AND _G.cw_name=hop)'''),
 
     # optional variable with additional restriction on inlined relation
     # XXX the expected result should be as the query below. So what, raise BadRQLQuery ?
     ('Any T,G,S WHERE T tags G?, G in_state S, S name "hop", G is CWUser',
-     '''SELECT T.cw_eid, G.cw_eid, S.cw_eid
-FROM cw_State AS S, cw_Tag AS T LEFT OUTER JOIN tags_relation AS rel_tags0 ON (rel_tags0.eid_from=T.cw_eid) LEFT OUTER JOIN cw_CWUser AS G ON (rel_tags0.eid_to=G.cw_eid)
-WHERE G.cw_in_state=S.cw_eid AND S.cw_name=hop
+     '''SELECT _T.cw_eid, _G.cw_eid, _S.cw_eid
+FROM cw_State AS _S, cw_Tag AS _T LEFT OUTER JOIN tags_relation AS rel_tags0 ON (rel_tags0.eid_from=_T.cw_eid) LEFT OUTER JOIN cw_CWUser AS _G ON (rel_tags0.eid_to=_G.cw_eid)
+WHERE _G.cw_in_state=_S.cw_eid AND _S.cw_name=hop
 '''),
 
     # optional variable with additional invariant restriction on an inlined relation
     ('Any T,G,S WHERE T tags G, G in_state S?, S eid 1, G is CWUser',
-     '''SELECT rel_tags0.eid_from, G.cw_eid, G.cw_in_state
-FROM cw_CWUser AS G, tags_relation AS rel_tags0
-WHERE rel_tags0.eid_to=G.cw_eid AND (G.cw_in_state=1 OR G.cw_in_state IS NULL)'''),
+     '''SELECT rel_tags0.eid_from, _G.cw_eid, _G.cw_in_state
+FROM cw_CWUser AS _G, tags_relation AS rel_tags0
+WHERE rel_tags0.eid_to=_G.cw_eid AND (_G.cw_in_state=1 OR _G.cw_in_state IS NULL)'''),
 
     # two optional variables with additional invariant restriction on an inlined relation
     ('Any T,G,S WHERE T tags G?, G in_state S?, S eid 1, G is CWUser',
-     '''SELECT T.cw_eid, G.cw_eid, G.cw_in_state
-FROM cw_Tag AS T LEFT OUTER JOIN tags_relation AS rel_tags0 ON (rel_tags0.eid_from=T.cw_eid) LEFT OUTER JOIN cw_CWUser AS G ON (rel_tags0.eid_to=G.cw_eid AND (G.cw_in_state=1 OR G.cw_in_state IS NULL))'''),
+     '''SELECT _T.cw_eid, _G.cw_eid, _G.cw_in_state
+FROM cw_Tag AS _T LEFT OUTER JOIN tags_relation AS rel_tags0 ON (rel_tags0.eid_from=_T.cw_eid) LEFT OUTER JOIN cw_CWUser AS _G ON (rel_tags0.eid_to=_G.cw_eid AND (_G.cw_in_state=1 OR _G.cw_in_state IS NULL))'''),
 
     # two optional variables with additional restriction on an inlined relation
     ('Any T,G,S WHERE T tags G?, G in_state S?, S name "hop", G is CWUser',
-     '''SELECT T.cw_eid, G.cw_eid, S.cw_eid
-FROM cw_Tag AS T LEFT OUTER JOIN tags_relation AS rel_tags0 ON (rel_tags0.eid_from=T.cw_eid) LEFT OUTER JOIN cw_CWUser AS G ON (rel_tags0.eid_to=G.cw_eid) LEFT OUTER JOIN cw_State AS S ON (G.cw_in_state=S.cw_eid AND S.cw_name=hop)'''),
+     '''SELECT _T.cw_eid, _G.cw_eid, _S.cw_eid
+FROM cw_Tag AS _T LEFT OUTER JOIN tags_relation AS rel_tags0 ON (rel_tags0.eid_from=_T.cw_eid) LEFT OUTER JOIN cw_CWUser AS _G ON (rel_tags0.eid_to=_G.cw_eid) LEFT OUTER JOIN cw_State AS _S ON (_G.cw_in_state=_S.cw_eid AND _S.cw_name=hop)'''),
 
     # two optional variables with additional restriction on an ambigous inlined relation
     ('Any T,G,S WHERE T tags G?, G in_state S?, S name "hop"',
      '''
-SELECT T.cw_eid, _T0.C0, _T0.C1
-FROM cw_Tag AS T LEFT OUTER JOIN tags_relation AS rel_tags0 ON (rel_tags0.eid_from=T.cw_eid) LEFT OUTER JOIN (SELECT G.cw_eid AS C0, S.cw_eid AS C1
-FROM cw_Affaire AS G LEFT OUTER JOIN cw_State AS S ON (G.cw_in_state=S.cw_eid AND S.cw_name=hop)
+SELECT _T.cw_eid, _T0.C0, _T0.C1
+FROM cw_Tag AS _T LEFT OUTER JOIN tags_relation AS rel_tags0 ON (rel_tags0.eid_from=_T.cw_eid) LEFT OUTER JOIN (SELECT _G.cw_eid AS C0, _S.cw_eid AS C1
+FROM cw_Affaire AS _G LEFT OUTER JOIN cw_State AS _S ON (_G.cw_in_state=_S.cw_eid AND _S.cw_name=hop)
 UNION ALL
-SELECT G.cw_eid AS C0, S.cw_eid AS C1
-FROM cw_CWUser AS G LEFT OUTER JOIN cw_State AS S ON (G.cw_in_state=S.cw_eid AND S.cw_name=hop)
+SELECT _G.cw_eid AS C0, _S.cw_eid AS C1
+FROM cw_CWUser AS _G LEFT OUTER JOIN cw_State AS _S ON (_G.cw_in_state=_S.cw_eid AND _S.cw_name=hop)
 UNION ALL
-SELECT G.cw_eid AS C0, S.cw_eid AS C1
-FROM cw_Note AS G LEFT OUTER JOIN cw_State AS S ON (G.cw_in_state=S.cw_eid AND S.cw_name=hop) ) AS _T0 ON (rel_tags0.eid_to=_T0.C0)'''),
+SELECT _G.cw_eid AS C0, _S.cw_eid AS C1
+FROM cw_Note AS _G LEFT OUTER JOIN cw_State AS _S ON (_G.cw_in_state=_S.cw_eid AND _S.cw_name=hop) ) AS _T0 ON (rel_tags0.eid_to=_T0.C0)'''),
 
     ('Any O,AD  WHERE NOT S inline1 O, S eid 123, O todo_by AD?',
-     '''SELECT O.cw_eid, rel_todo_by0.eid_to
-FROM cw_Affaire AS O LEFT OUTER JOIN todo_by_relation AS rel_todo_by0 ON (rel_todo_by0.eid_from=O.cw_eid), cw_Note AS S
-WHERE NOT EXISTS(SELECT 1 WHERE S.cw_inline1=O.cw_eid) AND S.cw_eid=123''')
+     '''SELECT _O.cw_eid, rel_todo_by0.eid_to
+FROM cw_Affaire AS _O LEFT OUTER JOIN todo_by_relation AS rel_todo_by0 ON (rel_todo_by0.eid_from=_O.cw_eid), cw_Note AS _S
+WHERE NOT EXISTS(SELECT 1 WHERE _S.cw_inline1=_O.cw_eid) AND _S.cw_eid=123''')
     ]
 
 VIRTUAL_VARS = [
     ("Personne P WHERE P travaille S, S tel T, S fax T, S is Societe;",
      '''SELECT rel_travaille0.eid_from
-FROM cw_Societe AS S, travaille_relation AS rel_travaille0
-WHERE rel_travaille0.eid_to=S.cw_eid AND S.cw_fax=S.cw_tel'''),
+FROM cw_Societe AS _S, travaille_relation AS rel_travaille0
+WHERE rel_travaille0.eid_to=_S.cw_eid AND _S.cw_fax=_S.cw_tel'''),
 
     ("Personne P where X eid 0, X creation_date D, P datenaiss < D, X is Affaire",
-     '''SELECT P.cw_eid
-FROM cw_Affaire AS X, cw_Personne AS P
-WHERE X.cw_eid=0 AND P.cw_datenaiss<X.cw_creation_date'''),
+     '''SELECT _P.cw_eid
+FROM cw_Affaire AS _X, cw_Personne AS _P
+WHERE _X.cw_eid=0 AND _P.cw_datenaiss<_X.cw_creation_date'''),
 
     ("Any N,T WHERE N is Note, N type T;",
-     '''SELECT N.cw_eid, N.cw_type
-FROM cw_Note AS N'''),
+     '''SELECT _N.cw_eid, _N.cw_type
+FROM cw_Note AS _N'''),
 
     ("Personne P where X is Personne, X tel T, X fax F, P fax T+F",
-     '''SELECT P.cw_eid
-FROM cw_Personne AS P, cw_Personne AS X
-WHERE P.cw_fax=(X.cw_tel + X.cw_fax)'''),
+     '''SELECT _P.cw_eid
+FROM cw_Personne AS _P, cw_Personne AS _X
+WHERE _P.cw_fax=(_X.cw_tel + _X.cw_fax)'''),
 
     ("Personne P where X tel T, X fax F, P fax IN (T,F)",
-     '''SELECT P.cw_eid
-FROM cw_Division AS X, cw_Personne AS P
-WHERE P.cw_fax IN(X.cw_tel, X.cw_fax)
+     '''SELECT _P.cw_eid
+FROM cw_Division AS _X, cw_Personne AS _P
+WHERE _P.cw_fax IN(_X.cw_tel, _X.cw_fax)
 UNION ALL
-SELECT P.cw_eid
-FROM cw_Personne AS P, cw_Personne AS X
-WHERE P.cw_fax IN(X.cw_tel, X.cw_fax)
+SELECT _P.cw_eid
+FROM cw_Personne AS _P, cw_Personne AS _X
+WHERE _P.cw_fax IN(_X.cw_tel, _X.cw_fax)
 UNION ALL
-SELECT P.cw_eid
-FROM cw_Personne AS P, cw_Societe AS X
-WHERE P.cw_fax IN(X.cw_tel, X.cw_fax)
+SELECT _P.cw_eid
+FROM cw_Personne AS _P, cw_Societe AS _X
+WHERE _P.cw_fax IN(_X.cw_tel, _X.cw_fax)
 UNION ALL
-SELECT P.cw_eid
-FROM cw_Personne AS P, cw_SubDivision AS X
-WHERE P.cw_fax IN(X.cw_tel, X.cw_fax)'''),
+SELECT _P.cw_eid
+FROM cw_Personne AS _P, cw_SubDivision AS _X
+WHERE _P.cw_fax IN(_X.cw_tel, _X.cw_fax)'''),
 
     ("Personne P where X tel T, X fax F, P fax IN (T,F,0832542332)",
-     '''SELECT P.cw_eid
-FROM cw_Division AS X, cw_Personne AS P
-WHERE P.cw_fax IN(X.cw_tel, X.cw_fax, 832542332)
+     '''SELECT _P.cw_eid
+FROM cw_Division AS _X, cw_Personne AS _P
+WHERE _P.cw_fax IN(_X.cw_tel, _X.cw_fax, 832542332)
 UNION ALL
-SELECT P.cw_eid
-FROM cw_Personne AS P, cw_Personne AS X
-WHERE P.cw_fax IN(X.cw_tel, X.cw_fax, 832542332)
+SELECT _P.cw_eid
+FROM cw_Personne AS _P, cw_Personne AS _X
+WHERE _P.cw_fax IN(_X.cw_tel, _X.cw_fax, 832542332)
 UNION ALL
-SELECT P.cw_eid
-FROM cw_Personne AS P, cw_Societe AS X
-WHERE P.cw_fax IN(X.cw_tel, X.cw_fax, 832542332)
+SELECT _P.cw_eid
+FROM cw_Personne AS _P, cw_Societe AS _X
+WHERE _P.cw_fax IN(_X.cw_tel, _X.cw_fax, 832542332)
 UNION ALL
-SELECT P.cw_eid
-FROM cw_Personne AS P, cw_SubDivision AS X
-WHERE P.cw_fax IN(X.cw_tel, X.cw_fax, 832542332)'''),
+SELECT _P.cw_eid
+FROM cw_Personne AS _P, cw_SubDivision AS _X
+WHERE _P.cw_fax IN(_X.cw_tel, _X.cw_fax, 832542332)'''),
     ]
 
 FUNCS = [
     ("Any COUNT(P) WHERE P is Personne",
-     '''SELECT COUNT(P.cw_eid)
-FROM cw_Personne AS P'''),
+     '''SELECT COUNT(_P.cw_eid)
+FROM cw_Personne AS _P'''),
     ]
 
 SYMETRIC = [
     ('Any P WHERE X eid 0, X connait P',
-     '''SELECT DISTINCT P.cw_eid
-FROM connait_relation AS rel_connait0, cw_Personne AS P
-WHERE (rel_connait0.eid_from=0 AND rel_connait0.eid_to=P.cw_eid OR rel_connait0.eid_to=0 AND rel_connait0.eid_from=P.cw_eid)'''
+     '''SELECT DISTINCT _P.cw_eid
+FROM connait_relation AS rel_connait0, cw_Personne AS _P
+WHERE (rel_connait0.eid_from=0 AND rel_connait0.eid_to=_P.cw_eid OR rel_connait0.eid_to=0 AND rel_connait0.eid_from=_P.cw_eid)'''
      ),
 
     ('Any P WHERE X connait P',
-    '''SELECT DISTINCT P.cw_eid
-FROM connait_relation AS rel_connait0, cw_Personne AS P
-WHERE (rel_connait0.eid_to=P.cw_eid OR rel_connait0.eid_from=P.cw_eid)'''
+    '''SELECT DISTINCT _P.cw_eid
+FROM connait_relation AS rel_connait0, cw_Personne AS _P
+WHERE (rel_connait0.eid_to=_P.cw_eid OR rel_connait0.eid_from=_P.cw_eid)'''
     ),
 
     ('Any X WHERE X connait P',
-    '''SELECT DISTINCT X.cw_eid
-FROM connait_relation AS rel_connait0, cw_Personne AS X
-WHERE (rel_connait0.eid_from=X.cw_eid OR rel_connait0.eid_to=X.cw_eid)'''
+    '''SELECT DISTINCT _X.cw_eid
+FROM connait_relation AS rel_connait0, cw_Personne AS _X
+WHERE (rel_connait0.eid_from=_X.cw_eid OR rel_connait0.eid_to=_X.cw_eid)'''
      ),
 
     ('Any P WHERE X eid 0, NOT X connait P',
-     '''SELECT P.cw_eid
-FROM cw_Personne AS P
-WHERE NOT EXISTS(SELECT 1 FROM connait_relation AS rel_connait0 WHERE (rel_connait0.eid_from=0 AND rel_connait0.eid_to=P.cw_eid OR rel_connait0.eid_to=0 AND rel_connait0.eid_from=P.cw_eid))'''),
+     '''SELECT _P.cw_eid
+FROM cw_Personne AS _P
+WHERE NOT EXISTS(SELECT 1 FROM connait_relation AS rel_connait0 WHERE (rel_connait0.eid_from=0 AND rel_connait0.eid_to=_P.cw_eid OR rel_connait0.eid_to=0 AND rel_connait0.eid_from=_P.cw_eid))'''),
 
     ('Any P WHERE NOT X connait P',
-    '''SELECT P.cw_eid
-FROM cw_Personne AS P
-WHERE NOT EXISTS(SELECT 1 FROM connait_relation AS rel_connait0 WHERE (rel_connait0.eid_to=P.cw_eid OR rel_connait0.eid_from=P.cw_eid))'''),
+    '''SELECT _P.cw_eid
+FROM cw_Personne AS _P
+WHERE NOT EXISTS(SELECT 1 FROM connait_relation AS rel_connait0 WHERE (rel_connait0.eid_to=_P.cw_eid OR rel_connait0.eid_from=_P.cw_eid))'''),
 
     ('Any X WHERE NOT X connait P',
-    '''SELECT X.cw_eid
-FROM cw_Personne AS X
-WHERE NOT EXISTS(SELECT 1 FROM connait_relation AS rel_connait0 WHERE (rel_connait0.eid_from=X.cw_eid OR rel_connait0.eid_to=X.cw_eid))'''),
+    '''SELECT _X.cw_eid
+FROM cw_Personne AS _X
+WHERE NOT EXISTS(SELECT 1 FROM connait_relation AS rel_connait0 WHERE (rel_connait0.eid_from=_X.cw_eid OR rel_connait0.eid_to=_X.cw_eid))'''),
 
     ('Any P WHERE X connait P, P nom "nom"',
-     '''SELECT DISTINCT P.cw_eid
-FROM connait_relation AS rel_connait0, cw_Personne AS P
-WHERE (rel_connait0.eid_to=P.cw_eid OR rel_connait0.eid_from=P.cw_eid) AND P.cw_nom=nom'''),
+     '''SELECT DISTINCT _P.cw_eid
+FROM connait_relation AS rel_connait0, cw_Personne AS _P
+WHERE (rel_connait0.eid_to=_P.cw_eid OR rel_connait0.eid_from=_P.cw_eid) AND _P.cw_nom=nom'''),
 
     ('Any X WHERE X connait P, P nom "nom"',
-     '''SELECT DISTINCT X.cw_eid
-FROM connait_relation AS rel_connait0, cw_Personne AS P, cw_Personne AS X
-WHERE (rel_connait0.eid_from=X.cw_eid AND rel_connait0.eid_to=P.cw_eid OR rel_connait0.eid_to=X.cw_eid AND rel_connait0.eid_from=P.cw_eid) AND P.cw_nom=nom'''
+     '''SELECT DISTINCT _X.cw_eid
+FROM connait_relation AS rel_connait0, cw_Personne AS _P, cw_Personne AS _X
+WHERE (rel_connait0.eid_from=_X.cw_eid AND rel_connait0.eid_to=_P.cw_eid OR rel_connait0.eid_to=_X.cw_eid AND rel_connait0.eid_from=_P.cw_eid) AND _P.cw_nom=nom'''
     ),
 
     ('Any X ORDERBY X DESC LIMIT 9 WHERE E eid 0, E connait X',
-    '''SELECT DISTINCT X.cw_eid
-FROM connait_relation AS rel_connait0, cw_Personne AS X
-WHERE (rel_connait0.eid_from=0 AND rel_connait0.eid_to=X.cw_eid OR rel_connait0.eid_to=0 AND rel_connait0.eid_from=X.cw_eid)
+    '''SELECT DISTINCT _X.cw_eid
+FROM connait_relation AS rel_connait0, cw_Personne AS _X
+WHERE (rel_connait0.eid_from=0 AND rel_connait0.eid_to=_X.cw_eid OR rel_connait0.eid_to=0 AND rel_connait0.eid_from=_X.cw_eid)
 ORDER BY 1 DESC
 LIMIT 9'''
      ),
 
     ('DISTINCT Any P WHERE P connait S OR S connait P, S nom "chouette"',
-     '''SELECT DISTINCT P.cw_eid
-FROM connait_relation AS rel_connait0, cw_Personne AS P, cw_Personne AS S
-WHERE (rel_connait0.eid_from=P.cw_eid AND rel_connait0.eid_to=S.cw_eid OR rel_connait0.eid_to=P.cw_eid AND rel_connait0.eid_from=S.cw_eid) AND S.cw_nom=chouette'''
+     '''SELECT DISTINCT _P.cw_eid
+FROM connait_relation AS rel_connait0, cw_Personne AS _P, cw_Personne AS _S
+WHERE (rel_connait0.eid_from=_P.cw_eid AND rel_connait0.eid_to=_S.cw_eid OR rel_connait0.eid_to=_P.cw_eid AND rel_connait0.eid_from=_S.cw_eid) AND _S.cw_nom=chouette'''
      )
     ]
 
 INLINE = [
     ('Any P, L WHERE N ecrit_par P, P nom L, N eid 0',
-     '''SELECT P.cw_eid, P.cw_nom
-FROM cw_Note AS N, cw_Personne AS P
-WHERE N.cw_ecrit_par=P.cw_eid AND N.cw_eid=0'''),
+     '''SELECT _P.cw_eid, _P.cw_nom
+FROM cw_Note AS _N, cw_Personne AS _P
+WHERE _N.cw_ecrit_par=_P.cw_eid AND _N.cw_eid=0'''),
 
     ('Any N WHERE NOT N ecrit_par P, P nom "toto"',
-     '''SELECT N.cw_eid
-FROM cw_Note AS N, cw_Personne AS P
-WHERE NOT EXISTS(SELECT 1 WHERE N.cw_ecrit_par=P.cw_eid) AND P.cw_nom=toto'''),
+     '''SELECT _N.cw_eid
+FROM cw_Note AS _N, cw_Personne AS _P
+WHERE NOT EXISTS(SELECT 1 WHERE _N.cw_ecrit_par=_P.cw_eid) AND _P.cw_nom=toto'''),
 
     ('Any P WHERE N ecrit_par P, N eid 0',
-    '''SELECT N.cw_ecrit_par
-FROM cw_Note AS N
-WHERE N.cw_ecrit_par IS NOT NULL AND N.cw_eid=0'''),
+    '''SELECT _N.cw_ecrit_par
+FROM cw_Note AS _N
+WHERE _N.cw_ecrit_par IS NOT NULL AND _N.cw_eid=0'''),
 
     ('Any P WHERE N ecrit_par P, P is Personne, N eid 0',
-    '''SELECT P.cw_eid
-FROM cw_Note AS N, cw_Personne AS P
-WHERE N.cw_ecrit_par=P.cw_eid AND N.cw_eid=0'''),
+    '''SELECT _P.cw_eid
+FROM cw_Note AS _N, cw_Personne AS _P
+WHERE _N.cw_ecrit_par=_P.cw_eid AND _N.cw_eid=0'''),
 
     ('Any P WHERE NOT N ecrit_par P, P is Personne, N eid 512',
-     '''SELECT P.cw_eid
-FROM cw_Note AS N, cw_Personne AS P
-WHERE NOT EXISTS(SELECT 1 WHERE N.cw_ecrit_par=P.cw_eid) AND N.cw_eid=512'''),
+     '''SELECT _P.cw_eid
+FROM cw_Note AS _N, cw_Personne AS _P
+WHERE NOT EXISTS(SELECT 1 WHERE _N.cw_ecrit_par=_P.cw_eid) AND _N.cw_eid=512'''),
 
     ('Any S,ES,T WHERE S state_of ET, ET name "CWUser", ES allowed_transition T, T destination_state S',
-     '''SELECT T.cw_destination_state, rel_allowed_transition1.eid_from, T.cw_eid
-FROM allowed_transition_relation AS rel_allowed_transition1, cw_Transition AS T, cw_Workflow AS ET, state_of_relation AS rel_state_of0
-WHERE T.cw_destination_state=rel_state_of0.eid_from AND rel_state_of0.eid_to=ET.cw_eid AND ET.cw_name=CWUser AND rel_allowed_transition1.eid_to=T.cw_eid'''),
+     '''SELECT _T.cw_destination_state, rel_allowed_transition1.eid_from, _T.cw_eid
+FROM allowed_transition_relation AS rel_allowed_transition1, cw_Transition AS _T, cw_Workflow AS _ET, state_of_relation AS rel_state_of0
+WHERE _T.cw_destination_state=rel_state_of0.eid_from AND rel_state_of0.eid_to=_ET.cw_eid AND _ET.cw_name=CWUser AND rel_allowed_transition1.eid_to=_T.cw_eid'''),
 
     ('Any O WHERE S eid 0, S in_state O',
-     '''SELECT S.cw_in_state
-FROM cw_Affaire AS S
-WHERE S.cw_eid=0 AND S.cw_in_state IS NOT NULL
+     '''SELECT _S.cw_in_state
+FROM cw_Affaire AS _S
+WHERE _S.cw_eid=0 AND _S.cw_in_state IS NOT NULL
 UNION ALL
-SELECT S.cw_in_state
-FROM cw_CWUser AS S
-WHERE S.cw_eid=0 AND S.cw_in_state IS NOT NULL
+SELECT _S.cw_in_state
+FROM cw_CWUser AS _S
+WHERE _S.cw_eid=0 AND _S.cw_in_state IS NOT NULL
 UNION ALL
-SELECT S.cw_in_state
-FROM cw_Note AS S
-WHERE S.cw_eid=0 AND S.cw_in_state IS NOT NULL''')
+SELECT _S.cw_in_state
+FROM cw_Note AS _S
+WHERE _S.cw_eid=0 AND _S.cw_in_state IS NOT NULL''')
 
     ]
 
 INTERSECT = [
     ('Any SN WHERE NOT X in_state S, S name SN',
-     '''SELECT S.cw_name
-FROM cw_State AS S
-WHERE NOT EXISTS(SELECT 1 FROM cw_Affaire AS X WHERE X.cw_in_state=S.cw_eid)
+     '''SELECT _S.cw_name
+FROM cw_State AS _S
+WHERE NOT EXISTS(SELECT 1 FROM cw_Affaire AS _X WHERE _X.cw_in_state=_S.cw_eid)
 INTERSECT
-SELECT S.cw_name
-FROM cw_State AS S
-WHERE NOT EXISTS(SELECT 1 FROM cw_CWUser AS X WHERE X.cw_in_state=S.cw_eid)
+SELECT _S.cw_name
+FROM cw_State AS _S
+WHERE NOT EXISTS(SELECT 1 FROM cw_CWUser AS _X WHERE _X.cw_in_state=_S.cw_eid)
 INTERSECT
-SELECT S.cw_name
-FROM cw_State AS S
-WHERE NOT EXISTS(SELECT 1 FROM cw_Note AS X WHERE X.cw_in_state=S.cw_eid)'''),
+SELECT _S.cw_name
+FROM cw_State AS _S
+WHERE NOT EXISTS(SELECT 1 FROM cw_Note AS _X WHERE _X.cw_in_state=_S.cw_eid)'''),
 
     ('Any PN WHERE NOT X travaille S, X nom PN, S is IN(Division, Societe)',
-     '''SELECT X.cw_nom
-FROM cw_Personne AS X
-WHERE NOT EXISTS(SELECT 1 FROM travaille_relation AS rel_travaille0,cw_Division AS S WHERE rel_travaille0.eid_from=X.cw_eid AND rel_travaille0.eid_to=S.cw_eid)
+     '''SELECT _X.cw_nom
+FROM cw_Personne AS _X
+WHERE NOT EXISTS(SELECT 1 FROM travaille_relation AS rel_travaille0,cw_Division AS _S WHERE rel_travaille0.eid_from=_X.cw_eid AND rel_travaille0.eid_to=_S.cw_eid)
 INTERSECT
-SELECT X.cw_nom
-FROM cw_Personne AS X
-WHERE NOT EXISTS(SELECT 1 FROM travaille_relation AS rel_travaille0,cw_Societe AS S WHERE rel_travaille0.eid_from=X.cw_eid AND rel_travaille0.eid_to=S.cw_eid)'''),
+SELECT _X.cw_nom
+FROM cw_Personne AS _X
+WHERE NOT EXISTS(SELECT 1 FROM travaille_relation AS rel_travaille0,cw_Societe AS _S WHERE rel_travaille0.eid_from=_X.cw_eid AND rel_travaille0.eid_to=_S.cw_eid)'''),
 
     ('Any PN WHERE NOT X travaille S, S nom PN, S is IN(Division, Societe)',
-     '''SELECT S.cw_nom
-FROM cw_Division AS S
-WHERE NOT EXISTS(SELECT 1 FROM travaille_relation AS rel_travaille0 WHERE rel_travaille0.eid_to=S.cw_eid)
+     '''SELECT _S.cw_nom
+FROM cw_Division AS _S
+WHERE NOT EXISTS(SELECT 1 FROM travaille_relation AS rel_travaille0 WHERE rel_travaille0.eid_to=_S.cw_eid)
 UNION ALL
-SELECT S.cw_nom
-FROM cw_Societe AS S
-WHERE NOT EXISTS(SELECT 1 FROM travaille_relation AS rel_travaille0 WHERE rel_travaille0.eid_to=S.cw_eid)'''),
+SELECT _S.cw_nom
+FROM cw_Societe AS _S
+WHERE NOT EXISTS(SELECT 1 FROM travaille_relation AS rel_travaille0 WHERE rel_travaille0.eid_to=_S.cw_eid)'''),
 
     ('Personne X WHERE NOT X travaille S, S nom "chouette"',
-     '''SELECT X.cw_eid
-FROM cw_Division AS S, cw_Personne AS X
-WHERE NOT EXISTS(SELECT 1 FROM travaille_relation AS rel_travaille0 WHERE rel_travaille0.eid_from=X.cw_eid AND rel_travaille0.eid_to=S.cw_eid) AND S.cw_nom=chouette
+     '''SELECT _X.cw_eid
+FROM cw_Division AS _S, cw_Personne AS _X
+WHERE NOT EXISTS(SELECT 1 FROM travaille_relation AS rel_travaille0 WHERE rel_travaille0.eid_from=_X.cw_eid AND rel_travaille0.eid_to=_S.cw_eid) AND _S.cw_nom=chouette
 UNION ALL
-SELECT X.cw_eid
-FROM cw_Personne AS X, cw_Societe AS S
-WHERE NOT EXISTS(SELECT 1 FROM travaille_relation AS rel_travaille0 WHERE rel_travaille0.eid_from=X.cw_eid AND rel_travaille0.eid_to=S.cw_eid) AND S.cw_nom=chouette
+SELECT _X.cw_eid
+FROM cw_Personne AS _X, cw_Societe AS _S
+WHERE NOT EXISTS(SELECT 1 FROM travaille_relation AS rel_travaille0 WHERE rel_travaille0.eid_from=_X.cw_eid AND rel_travaille0.eid_to=_S.cw_eid) AND _S.cw_nom=chouette
 UNION ALL
-SELECT X.cw_eid
-FROM cw_Personne AS X, cw_SubDivision AS S
-WHERE NOT EXISTS(SELECT 1 FROM travaille_relation AS rel_travaille0 WHERE rel_travaille0.eid_from=X.cw_eid AND rel_travaille0.eid_to=S.cw_eid) AND S.cw_nom=chouette'''),
+SELECT _X.cw_eid
+FROM cw_Personne AS _X, cw_SubDivision AS _S
+WHERE NOT EXISTS(SELECT 1 FROM travaille_relation AS rel_travaille0 WHERE rel_travaille0.eid_from=_X.cw_eid AND rel_travaille0.eid_to=_S.cw_eid) AND _S.cw_nom=chouette'''),
 
     ('Any X WHERE X is ET, ET eid 2',
      '''SELECT rel_is0.eid_from
@@ -1143,13 +1170,13 @@
 
     def test1(self):
         self._checkall('Any count(RDEF) WHERE RDEF relation_type X, X eid %(x)s',
-                       ("""SELECT COUNT(T1.C0) FROM (SELECT RDEF.cw_eid AS C0
-FROM cw_CWAttribute AS RDEF
-WHERE RDEF.cw_relation_type=%(x)s
+                       ("""SELECT COUNT(T1.C0) FROM (SELECT _RDEF.cw_eid AS C0
+FROM cw_CWAttribute AS _RDEF
+WHERE _RDEF.cw_relation_type=%(x)s
 UNION ALL
-SELECT RDEF.cw_eid AS C0
-FROM cw_CWRelation AS RDEF
-WHERE RDEF.cw_relation_type=%(x)s) AS T1""", {}),
+SELECT _RDEF.cw_eid AS C0
+FROM cw_CWRelation AS _RDEF
+WHERE _RDEF.cw_relation_type=%(x)s) AS T1""", {}),
                        )
 
     def test2(self):
@@ -1173,15 +1200,15 @@
     def test_varmap1(self):
         self._check('Any X,L WHERE X is CWUser, X in_group G, X login L, G name "users"',
                     '''SELECT T00.x, T00.l
-FROM T00, cw_CWGroup AS G, in_group_relation AS rel_in_group0
-WHERE rel_in_group0.eid_from=T00.x AND rel_in_group0.eid_to=G.cw_eid AND G.cw_name=users''',
+FROM T00, cw_CWGroup AS _G, in_group_relation AS rel_in_group0
+WHERE rel_in_group0.eid_from=T00.x AND rel_in_group0.eid_to=_G.cw_eid AND _G.cw_name=users''',
                     varmap={'X': 'T00.x', 'X.login': 'T00.l'})
 
     def test_varmap2(self):
         self._check('Any X,L,GN WHERE X is CWUser, X in_group G, X login L, G name GN',
-                    '''SELECT T00.x, T00.l, G.cw_name
-FROM T00, cw_CWGroup AS G, in_group_relation AS rel_in_group0
-WHERE rel_in_group0.eid_from=T00.x AND rel_in_group0.eid_to=G.cw_eid''',
+                    '''SELECT T00.x, T00.l, _G.cw_name
+FROM T00, cw_CWGroup AS _G, in_group_relation AS rel_in_group0
+WHERE rel_in_group0.eid_from=T00.x AND rel_in_group0.eid_to=_G.cw_eid''',
                     varmap={'X': 'T00.x', 'X.login': 'T00.l'})
 
     def test_varmap3(self):
@@ -1194,9 +1221,9 @@
         union = self._prepare('Any X WHERE X login %(login)s')
         r, args = self.o.generate(union, {'login': None})
         self.assertLinesEquals((r % args).strip(),
-                               '''SELECT X.cw_eid
-FROM cw_CWUser AS X
-WHERE X.cw_login IS NULL''')
+                               '''SELECT _X.cw_eid
+FROM cw_CWUser AS _X
+WHERE _X.cw_login IS NULL''')
 
     def test_parser_parse(self):
         for t in self._parse(PARSER):
@@ -1239,12 +1266,12 @@
             ('(Any N ORDERBY 1 WHERE X name N, X is State)'
              ' UNION '
              '(Any NN ORDERBY 1 WHERE XX name NN, XX is Transition)',
-             '''(SELECT X.cw_name
-FROM cw_State AS X
+             '''(SELECT _X.cw_name
+FROM cw_State AS _X
 ORDER BY 1)
 UNION ALL
-(SELECT XX.cw_name
-FROM cw_Transition AS XX
+(SELECT _XX.cw_name
+FROM cw_Transition AS _XX
 ORDER BY 1)'''),
             )):
             yield t
@@ -1257,11 +1284,11 @@
              ' UNION '
              '(Any NN WHERE XX name NN, XX is Transition))',
              '''SELECT _T0.C0
-FROM ((SELECT X.cw_name AS C0
-FROM cw_State AS X)
+FROM ((SELECT _X.cw_name AS C0
+FROM cw_State AS _X)
 UNION ALL
-(SELECT XX.cw_name AS C0
-FROM cw_Transition AS XX)) AS _T0
+(SELECT _XX.cw_name AS C0
+FROM cw_Transition AS _XX)) AS _T0
 ORDER BY 1'''),
 
             ('Any N,NX ORDERBY NX WITH N,NX BEING '
@@ -1269,40 +1296,40 @@
              ' UNION '
              '(Any N,COUNT(X) GROUPBY N WHERE X name N, X is Transition HAVING COUNT(X)>1))',
              '''SELECT _T0.C0, _T0.C1
-FROM ((SELECT X.cw_name AS C0, COUNT(X.cw_eid) AS C1
-FROM cw_State AS X
-GROUP BY X.cw_name
-HAVING COUNT(X.cw_eid)>1)
+FROM ((SELECT _X.cw_name AS C0, COUNT(_X.cw_eid) AS C1
+FROM cw_State AS _X
+GROUP BY _X.cw_name
+HAVING COUNT(_X.cw_eid)>1)
 UNION ALL
-(SELECT X.cw_name AS C0, COUNT(X.cw_eid) AS C1
-FROM cw_Transition AS X
-GROUP BY X.cw_name
-HAVING COUNT(X.cw_eid)>1)) AS _T0
+(SELECT _X.cw_name AS C0, COUNT(_X.cw_eid) AS C1
+FROM cw_Transition AS _X
+GROUP BY _X.cw_name
+HAVING COUNT(_X.cw_eid)>1)) AS _T0
 ORDER BY 2'''),
 
             ('Any N,COUNT(X) GROUPBY N HAVING COUNT(X)>1 '
              'WITH X, N BEING ((Any X, N WHERE X name N, X is State) UNION '
              '                 (Any X, N WHERE X name N, X is Transition))',
              '''SELECT _T0.C1, COUNT(_T0.C0)
-FROM ((SELECT X.cw_eid AS C0, X.cw_name AS C1
-FROM cw_State AS X)
+FROM ((SELECT _X.cw_eid AS C0, _X.cw_name AS C1
+FROM cw_State AS _X)
 UNION ALL
-(SELECT X.cw_eid AS C0, X.cw_name AS C1
-FROM cw_Transition AS X)) AS _T0
+(SELECT _X.cw_eid AS C0, _X.cw_name AS C1
+FROM cw_Transition AS _X)) AS _T0
 GROUP BY _T0.C1
 HAVING COUNT(_T0.C0)>1'''),
 
             ('Any ETN,COUNT(X) GROUPBY ETN WHERE X is ET, ET name ETN '
              'WITH X BEING ((Any X WHERE X is Societe) UNION (Any X WHERE X is Affaire, (EXISTS(X owned_by 1)) OR ((EXISTS(D concerne B?, B owned_by 1, X identity D, B is Note)) OR (EXISTS(F concerne E?, E owned_by 1, E is Societe, X identity F)))))',
-             '''SELECT ET.cw_name, COUNT(_T0.C0)
-FROM ((SELECT X.cw_eid AS C0
-FROM cw_Societe AS X)
+             '''SELECT _ET.cw_name, COUNT(_T0.C0)
+FROM ((SELECT _X.cw_eid AS C0
+FROM cw_Societe AS _X)
 UNION ALL
-(SELECT X.cw_eid AS C0
-FROM cw_Affaire AS X
-WHERE ((EXISTS(SELECT 1 FROM owned_by_relation AS rel_owned_by0 WHERE rel_owned_by0.eid_from=X.cw_eid AND rel_owned_by0.eid_to=1)) OR (((EXISTS(SELECT 1 FROM cw_Affaire AS D LEFT OUTER JOIN concerne_relation AS rel_concerne1 ON (rel_concerne1.eid_from=D.cw_eid) LEFT OUTER JOIN cw_Note AS B ON (rel_concerne1.eid_to=B.cw_eid), owned_by_relation AS rel_owned_by2 WHERE rel_owned_by2.eid_from=B.cw_eid AND rel_owned_by2.eid_to=1 AND X.cw_eid=D.cw_eid)) OR (EXISTS(SELECT 1 FROM cw_Affaire AS F LEFT OUTER JOIN concerne_relation AS rel_concerne3 ON (rel_concerne3.eid_from=F.cw_eid) LEFT OUTER JOIN cw_Societe AS E ON (rel_concerne3.eid_to=E.cw_eid), owned_by_relation AS rel_owned_by4 WHERE rel_owned_by4.eid_from=E.cw_eid AND rel_owned_by4.eid_to=1 AND X.cw_eid=F.cw_eid))))))) AS _T0, cw_CWEType AS ET, is_relation AS rel_is0
-WHERE rel_is0.eid_from=_T0.C0 AND rel_is0.eid_to=ET.cw_eid
-GROUP BY ET.cw_name'''),
+(SELECT _X.cw_eid AS C0
+FROM cw_Affaire AS _X
+WHERE ((EXISTS(SELECT 1 FROM owned_by_relation AS rel_owned_by0 WHERE rel_owned_by0.eid_from=_X.cw_eid AND rel_owned_by0.eid_to=1)) OR (((EXISTS(SELECT 1 FROM cw_Affaire AS _D LEFT OUTER JOIN concerne_relation AS rel_concerne1 ON (rel_concerne1.eid_from=_D.cw_eid) LEFT OUTER JOIN cw_Note AS _B ON (rel_concerne1.eid_to=_B.cw_eid), owned_by_relation AS rel_owned_by2 WHERE rel_owned_by2.eid_from=_B.cw_eid AND rel_owned_by2.eid_to=1 AND _X.cw_eid=_D.cw_eid)) OR (EXISTS(SELECT 1 FROM cw_Affaire AS _F LEFT OUTER JOIN concerne_relation AS rel_concerne3 ON (rel_concerne3.eid_from=_F.cw_eid) LEFT OUTER JOIN cw_Societe AS _E ON (rel_concerne3.eid_to=_E.cw_eid), owned_by_relation AS rel_owned_by4 WHERE rel_owned_by4.eid_from=_E.cw_eid AND rel_owned_by4.eid_to=1 AND _X.cw_eid=_F.cw_eid))))))) AS _T0, cw_CWEType AS _ET, is_relation AS rel_is0
+WHERE rel_is0.eid_from=_T0.C0 AND rel_is0.eid_to=_ET.cw_eid
+GROUP BY _ET.cw_name'''),
             )):
             yield t
 
@@ -1331,29 +1358,29 @@
 WHERE appears0.words @@ to_tsquery('default', 'toto&tata')"""),
 
             ('Personne X WHERE X has_text "toto tata"',
-             """SELECT X.eid
-FROM appears AS appears0, entities AS X
-WHERE appears0.words @@ to_tsquery('default', 'toto&tata') AND appears0.uid=X.eid AND X.type='Personne'"""),
+             """SELECT _X.eid
+FROM appears AS appears0, entities AS _X
+WHERE appears0.words @@ to_tsquery('default', 'toto&tata') AND appears0.uid=_X.eid AND _X.type='Personne'"""),
 
             ('Personne X WHERE X has_text %(text)s',
-             """SELECT X.eid
-FROM appears AS appears0, entities AS X
-WHERE appears0.words @@ to_tsquery('default', 'hip&hop&momo') AND appears0.uid=X.eid AND X.type='Personne'"""),
+             """SELECT _X.eid
+FROM appears AS appears0, entities AS _X
+WHERE appears0.words @@ to_tsquery('default', 'hip&hop&momo') AND appears0.uid=_X.eid AND _X.type='Personne'"""),
 
             ('Any X WHERE X has_text "toto tata", X name "tutu", X is IN (Basket,Folder)',
-             """SELECT X.cw_eid
-FROM appears AS appears0, cw_Basket AS X
-WHERE appears0.words @@ to_tsquery('default', 'toto&tata') AND appears0.uid=X.cw_eid AND X.cw_name=tutu
+             """SELECT _X.cw_eid
+FROM appears AS appears0, cw_Basket AS _X
+WHERE appears0.words @@ to_tsquery('default', 'toto&tata') AND appears0.uid=_X.cw_eid AND _X.cw_name=tutu
 UNION ALL
-SELECT X.cw_eid
-FROM appears AS appears0, cw_Folder AS X
-WHERE appears0.words @@ to_tsquery('default', 'toto&tata') AND appears0.uid=X.cw_eid AND X.cw_name=tutu
+SELECT _X.cw_eid
+FROM appears AS appears0, cw_Folder AS _X
+WHERE appears0.words @@ to_tsquery('default', 'toto&tata') AND appears0.uid=_X.cw_eid AND _X.cw_name=tutu
 """),
 
             ('Personne X where X has_text %(text)s, X travaille S, S has_text %(text)s',
-             """SELECT X.eid
-FROM appears AS appears0, appears AS appears2, entities AS X, travaille_relation AS rel_travaille1
-WHERE appears0.words @@ to_tsquery('default', 'hip&hop&momo') AND appears0.uid=X.eid AND X.type='Personne' AND X.eid=rel_travaille1.eid_from AND appears2.uid=rel_travaille1.eid_to AND appears2.words @@ to_tsquery('default', 'hip&hop&momo')"""),
+             """SELECT _X.eid
+FROM appears AS appears0, appears AS appears2, entities AS _X, travaille_relation AS rel_travaille1
+WHERE appears0.words @@ to_tsquery('default', 'hip&hop&momo') AND appears0.uid=_X.eid AND _X.type='Personne' AND _X.eid=rel_travaille1.eid_from AND appears2.uid=rel_travaille1.eid_to AND appears2.words @@ to_tsquery('default', 'hip&hop&momo')"""),
             )):
             yield t
 
@@ -1361,7 +1388,7 @@
     def test_from_clause_needed(self):
         queries = [("Any 1 WHERE EXISTS(T is CWGroup, T name 'managers')",
                     '''SELECT 1
-WHERE EXISTS(SELECT 1 FROM cw_CWGroup AS T WHERE T.cw_name=managers)'''),
+WHERE EXISTS(SELECT 1 FROM cw_CWGroup AS _T WHERE _T.cw_name=managers)'''),
                    ('Any X,Y WHERE NOT X created_by Y, X eid 5, Y eid 6',
                     '''SELECT 5, 6
 WHERE NOT EXISTS(SELECT 1 FROM created_by_relation AS rel_created_by0 WHERE rel_created_by0.eid_from=5 AND rel_created_by0.eid_to=6)'''),
@@ -1372,7 +1399,7 @@
     def test_ambigous_exists_no_from_clause(self):
         self._check('Any COUNT(U) WHERE U eid 1, EXISTS (P owned_by U, P is IN (Note, Affaire))',
                     '''SELECT COUNT(1)
-WHERE EXISTS(SELECT 1 FROM owned_by_relation AS rel_owned_by0, cw_Affaire AS P WHERE rel_owned_by0.eid_from=P.cw_eid AND rel_owned_by0.eid_to=1 UNION SELECT 1 FROM owned_by_relation AS rel_owned_by1, cw_Note AS P WHERE rel_owned_by1.eid_from=P.cw_eid AND rel_owned_by1.eid_to=1)''')
+WHERE EXISTS(SELECT 1 FROM owned_by_relation AS rel_owned_by0, cw_Affaire AS _P WHERE rel_owned_by0.eid_from=_P.cw_eid AND rel_owned_by0.eid_to=1 UNION SELECT 1 FROM owned_by_relation AS rel_owned_by1, cw_Note AS _P WHERE rel_owned_by1.eid_from=_P.cw_eid AND rel_owned_by1.eid_to=1)''')
 
     def test_attr_map(self):
         def generate_ref(gen, linkedvar, rel):
@@ -1381,12 +1408,12 @@
         self.o.attr_map['Affaire.ref'] = generate_ref
         try:
             self._check('Any R WHERE X ref R',
-                        '''SELECT VERSION_DATA(X.cw_eid)
-FROM cw_Affaire AS X''')
+                        '''SELECT VERSION_DATA(_X.cw_eid)
+FROM cw_Affaire AS _X''')
             self._check('Any X WHERE X ref 1',
-                        '''SELECT X.cw_eid
-FROM cw_Affaire AS X
-WHERE VERSION_DATA(X.cw_eid)=1''')
+                        '''SELECT _X.cw_eid
+FROM cw_Affaire AS _X
+WHERE VERSION_DATA(_X.cw_eid)=1''')
         finally:
             self.o.attr_map.clear()
 
@@ -1411,12 +1438,12 @@
             ('(Any N ORDERBY 1 WHERE X name N, X is State)'
              ' UNION '
              '(Any NN ORDERBY 1 WHERE XX name NN, XX is Transition)',
-             '''SELECT X.cw_name
-FROM cw_State AS X
+             '''SELECT _X.cw_name
+FROM cw_State AS _X
 ORDER BY 1
 UNION ALL
-SELECT XX.cw_name
-FROM cw_Transition AS XX
+SELECT _XX.cw_name
+FROM cw_Transition AS _XX
 ORDER BY 1'''),
             )):
             yield t
@@ -1431,11 +1458,11 @@
              ' UNION '
              '(Any NN WHERE XX name NN, XX is Transition))',
              '''SELECT _T0.C0
-FROM (SELECT X.cw_name AS C0
-FROM cw_State AS X
+FROM (SELECT _X.cw_name AS C0
+FROM cw_State AS _X
 UNION ALL
-SELECT XX.cw_name AS C0
-FROM cw_Transition AS XX) AS _T0
+SELECT _XX.cw_name AS C0
+FROM cw_Transition AS _XX) AS _T0
 ORDER BY 1'''),
 
             ('Any N,NX ORDERBY NX WITH N,NX BEING '
@@ -1443,26 +1470,26 @@
              ' UNION '
              '(Any N,COUNT(X) GROUPBY N WHERE X name N, X is Transition HAVING COUNT(X)>1))',
              '''SELECT _T0.C0, _T0.C1
-FROM (SELECT X.cw_name AS C0, COUNT(X.cw_eid) AS C1
-FROM cw_State AS X
-GROUP BY X.cw_name
-HAVING COUNT(X.cw_eid)>1
+FROM (SELECT _X.cw_name AS C0, COUNT(_X.cw_eid) AS C1
+FROM cw_State AS _X
+GROUP BY _X.cw_name
+HAVING COUNT(_X.cw_eid)>1
 UNION ALL
-SELECT X.cw_name AS C0, COUNT(X.cw_eid) AS C1
-FROM cw_Transition AS X
-GROUP BY X.cw_name
-HAVING COUNT(X.cw_eid)>1) AS _T0
+SELECT _X.cw_name AS C0, COUNT(_X.cw_eid) AS C1
+FROM cw_Transition AS _X
+GROUP BY _X.cw_name
+HAVING COUNT(_X.cw_eid)>1) AS _T0
 ORDER BY 2'''),
 
             ('Any N,COUNT(X) GROUPBY N HAVING COUNT(X)>1 '
              'WITH X, N BEING ((Any X, N WHERE X name N, X is State) UNION '
              '                 (Any X, N WHERE X name N, X is Transition))',
              '''SELECT _T0.C1, COUNT(_T0.C0)
-FROM (SELECT X.cw_eid AS C0, X.cw_name AS C1
-FROM cw_State AS X
+FROM (SELECT _X.cw_eid AS C0, _X.cw_name AS C1
+FROM cw_State AS _X
 UNION ALL
-SELECT X.cw_eid AS C0, X.cw_name AS C1
-FROM cw_Transition AS X) AS _T0
+SELECT _X.cw_eid AS C0, _X.cw_name AS C1
+FROM cw_Transition AS _X) AS _T0
 GROUP BY _T0.C1
 HAVING COUNT(_T0.C0)>1'''),
             )):
@@ -1481,18 +1508,18 @@
 WHERE appears0.word_id IN (SELECT word_id FROM word WHERE word in ('hip', 'hop', 'momo'))"""),
 
             ('Personne X WHERE X has_text "toto tata"',
-             """SELECT X.eid
-FROM appears AS appears0, entities AS X
-WHERE appears0.word_id IN (SELECT word_id FROM word WHERE word in ('toto', 'tata')) AND appears0.uid=X.eid AND X.type='Personne'"""),
+             """SELECT _X.eid
+FROM appears AS appears0, entities AS _X
+WHERE appears0.word_id IN (SELECT word_id FROM word WHERE word in ('toto', 'tata')) AND appears0.uid=_X.eid AND _X.type='Personne'"""),
 
             ('Any X WHERE X has_text "toto tata", X name "tutu", X is IN (Basket,Folder)',
-             """SELECT X.cw_eid
-FROM appears AS appears0, cw_Basket AS X
-WHERE appears0.word_id IN (SELECT word_id FROM word WHERE word in ('toto', 'tata')) AND appears0.uid=X.cw_eid AND X.cw_name=tutu
+             """SELECT _X.cw_eid
+FROM appears AS appears0, cw_Basket AS _X
+WHERE appears0.word_id IN (SELECT word_id FROM word WHERE word in ('toto', 'tata')) AND appears0.uid=_X.cw_eid AND _X.cw_name=tutu
 UNION ALL
-SELECT X.cw_eid
-FROM appears AS appears0, cw_Folder AS X
-WHERE appears0.word_id IN (SELECT word_id FROM word WHERE word in ('toto', 'tata')) AND appears0.uid=X.cw_eid AND X.cw_name=tutu
+SELECT _X.cw_eid
+FROM appears AS appears0, cw_Folder AS _X
+WHERE appears0.word_id IN (SELECT word_id FROM word WHERE word in ('toto', 'tata')) AND appears0.uid=_X.cw_eid AND _X.cw_name=tutu
 """),
             )):
             yield t
@@ -1518,7 +1545,7 @@
         queries = [("Any 1 WHERE EXISTS(T is CWGroup, T name 'managers')",
                     '''SELECT 1
 FROM (SELECT 1) AS _T
-WHERE EXISTS(SELECT 1 FROM cw_CWGroup AS T WHERE T.cw_name=managers)'''),
+WHERE EXISTS(SELECT 1 FROM cw_CWGroup AS _T WHERE _T.cw_name=managers)'''),
                    ('Any X,Y WHERE NOT X created_by Y, X eid 5, Y eid 6',
                     '''SELECT 5, 6
 FROM (SELECT 1) AS _T
@@ -1535,21 +1562,21 @@
 FROM appears AS appears0
 WHERE MATCH (appears0.words) AGAINST ('toto tata' IN BOOLEAN MODE)"""),
             ('Personne X WHERE X has_text "toto tata"',
-             """SELECT X.eid
-FROM appears AS appears0, entities AS X
-WHERE MATCH (appears0.words) AGAINST ('toto tata' IN BOOLEAN MODE) AND appears0.uid=X.eid AND X.type='Personne'"""),
+             """SELECT _X.eid
+FROM appears AS appears0, entities AS _X
+WHERE MATCH (appears0.words) AGAINST ('toto tata' IN BOOLEAN MODE) AND appears0.uid=_X.eid AND _X.type='Personne'"""),
             ('Personne X WHERE X has_text %(text)s',
-             """SELECT X.eid
-FROM appears AS appears0, entities AS X
-WHERE MATCH (appears0.words) AGAINST ('hip hop momo' IN BOOLEAN MODE) AND appears0.uid=X.eid AND X.type='Personne'"""),
+             """SELECT _X.eid
+FROM appears AS appears0, entities AS _X
+WHERE MATCH (appears0.words) AGAINST ('hip hop momo' IN BOOLEAN MODE) AND appears0.uid=_X.eid AND _X.type='Personne'"""),
             ('Any X WHERE X has_text "toto tata", X name "tutu", X is IN (Basket,Folder)',
-             """SELECT X.cw_eid
-FROM appears AS appears0, cw_Basket AS X
-WHERE MATCH (appears0.words) AGAINST ('toto tata' IN BOOLEAN MODE) AND appears0.uid=X.cw_eid AND X.cw_name=tutu
+             """SELECT _X.cw_eid
+FROM appears AS appears0, cw_Basket AS _X
+WHERE MATCH (appears0.words) AGAINST ('toto tata' IN BOOLEAN MODE) AND appears0.uid=_X.cw_eid AND _X.cw_name=tutu
 UNION ALL
-SELECT X.cw_eid
-FROM appears AS appears0, cw_Folder AS X
-WHERE MATCH (appears0.words) AGAINST ('toto tata' IN BOOLEAN MODE) AND appears0.uid=X.cw_eid AND X.cw_name=tutu
+SELECT _X.cw_eid
+FROM appears AS appears0, cw_Folder AS _X
+WHERE MATCH (appears0.words) AGAINST ('toto tata' IN BOOLEAN MODE) AND appears0.uid=_X.cw_eid AND _X.cw_name=tutu
 """)
             ]
         for t in self._parse(queries):
@@ -1560,7 +1587,7 @@
         self._check('Any COUNT(U) WHERE U eid 1, EXISTS (P owned_by U, P is IN (Note, Affaire))',
                     '''SELECT COUNT(1)
 FROM (SELECT 1) AS _T
-WHERE EXISTS(SELECT 1 FROM owned_by_relation AS rel_owned_by0, cw_Affaire AS P WHERE rel_owned_by0.eid_from=P.cw_eid AND rel_owned_by0.eid_to=1 UNION SELECT 1 FROM owned_by_relation AS rel_owned_by1, cw_Note AS P WHERE rel_owned_by1.eid_from=P.cw_eid AND rel_owned_by1.eid_to=1)''')
+WHERE EXISTS(SELECT 1 FROM owned_by_relation AS rel_owned_by0, cw_Affaire AS _P WHERE rel_owned_by0.eid_from=_P.cw_eid AND rel_owned_by0.eid_to=1 UNION SELECT 1 FROM owned_by_relation AS rel_owned_by1, cw_Note AS _P WHERE rel_owned_by1.eid_from=_P.cw_eid AND rel_owned_by1.eid_to=1)''')
 
 
 
--- a/test/unittest_entity.py	Mon Oct 19 20:22:01 2009 +0200
+++ b/test/unittest_entity.py	Wed Oct 21 17:32:20 2009 +0200
@@ -196,7 +196,7 @@
                           'X modification_date AA')
         self.assertEquals(tag.related_rql('tags', 'subject', ('Personne',)),
                           'Any X,AA,AB ORDERBY AA ASC '
-                          'WHERE E eid %(x)s, E tags XE is IN (Personne), X nom AA, '
+                          'WHERE E eid %(x)s, E tags X, X is IN (Personne), X nom AA, '
                           'X modification_date AB')
 
     def test_unrelated_rql_security_1(self):
--- a/web/__init__.py	Mon Oct 19 20:22:01 2009 +0200
+++ b/web/__init__.py	Wed Oct 21 17:32:20 2009 +0200
@@ -10,15 +10,13 @@
 __docformat__ = "restructuredtext en"
 _ = unicode
 
-from decimal import Decimal
-from datetime import datetime, date, timedelta
 from simplejson import dumps
 from urllib import quote as urlquote
 
 from logilab.common.deprecation import deprecated
 
 from cubicweb.web._exceptions import *
-
+from cubicweb.utils import CubicWebJsonEncoder
 
 INTERNAL_FIELD_VALUE = '__cubicweb_internal_field__'
 
@@ -47,22 +45,16 @@
 FACETTES = set()
 
 
-
 def json_dumps(value):
-    if isinstance(value, Decimal):
-        value = float(value)
-    elif isinstance(value, (date, datetime)):
-        value = value.strftime('%Y-%m-%d %H:%M')
-    elif isinstance(value, timedelta):
-        value = (value.days * 24*60*60) + value.seconds
-    try:
-        return dumps(value)
-    except TypeError:
-        return dumps(repr(value))
+    return dumps(value, cls=CubicWebJsonEncoder)
 
 def jsonize(function):
     def newfunc(*args, **kwargs):
-        return json_dumps(function(*args, **kwargs))
+        value = function(*args, **kwargs)
+        try:
+            return json_dumps(value)
+        except TypeError:
+            return json_dumps(repr(value))
     return newfunc
 
 @deprecated('[3.4] use req.build_ajax_replace_url() instead')
--- a/web/component.py	Mon Oct 19 20:22:01 2009 +0200
+++ b/web/component.py	Wed Oct 21 17:32:20 2009 +0200
@@ -173,7 +173,8 @@
         if not rset.rowcount:
             return
         self.w(u'<div class="%s">' % self.div_class())
-        self.wview(self.vid, rset, title=self._cw._(self.title).capitalize())
+        self.w(u'<h4>%s</h4>\n' % self._cw._(self.title).capitalize())
+        self.wview(self.vid, rset)
         self.w(u'</div>')
 
 
--- a/web/data/cubicweb.edition.js	Mon Oct 19 20:22:01 2009 +0200
+++ b/web/data/cubicweb.edition.js	Wed Oct 21 17:32:20 2009 +0200
@@ -465,45 +465,6 @@
  * @param default_value : value if the field is empty
  * @param lzone : html fragment (string) for a clic-zone triggering actual edition
  */
-function inlineValidateAttributeForm(rtype, eid, divid, reload, default_value) {
-    try {
-	var form = getNode(divid+'-form');
-	if (typeof FCKeditorAPI != "undefined") {
-	    for ( var name in FCKeditorAPI.__Instances ) {
-		var oEditor = FCKeditorAPI.__Instances[name] ;
-		if ( oEditor.GetParentForm() == form ) {
-		    oEditor.UpdateLinkedField();
-		}
-	    }
-	}
-	var zipped = formContents(form);
-	var d = asyncRemoteExec('edit_field', 'apply', zipped[0], zipped[1],
-                                rtype, eid, default_value);
-    } catch (ex) {
-	log('got exception', ex);
-	return false;
-    }
-    d.addCallback(function (result, req) {
-        if (handleFormValidationResponse(divid+'-form', noop, noop, result)) {
-          if (reload) {
-	    document.location.href = result[1].split('?')[0];
-	  } else {
-	    var fieldview = getNode('value-' + divid);
-	    // XXX using innerHTML is very fragile and won't work if
-	    // we mix XHTML and HTML
-	    fieldview.innerHTML = result[2];
-	    // switch inline form off only if no error
-	    if (result[0]) {
-		// hide global error messages
-		hideInlineEdit(eid, rtype, divid);
-	    }
-	  }
-        }
-	return false;
-    });
-    return false;
-}
-
 function inlineValidateRelationForm(rtype, role, eid, divid, reload, vid,
                                     default_value, lzone) {
     try {
@@ -518,13 +479,11 @@
     d.addCallback(function (result, req) {
 	if (handleFormValidationResponse(divid+'-form', noop, noop, result)) {
           if (reload) {
-            document.location.href = result[1].split('?')[0];
+            document.location.reload();
           } else {
-            var d = asyncRemoteExec('reledit_form', eid, rtype, role, default_value, lzone);
-            d.addCallback(function (result) {
-              // XXX brittle ... replace with loadxhtml
-              jQuery('#'+divid+'-reledit').replaceWith(result);
-            });
+              var args = {fname: 'reledit_form', rtype: rtype, role: role, eid: eid, divid: divid,
+                          reload: reload, vid: vid, default_value: default_value, landing_zone: lzone};
+              jQuery('#'+divid+'-reledit').parent().loadxhtml(JSON_BASE_URL, args, 'post');
           }
 	}
         return false;
@@ -534,16 +493,26 @@
 
 
 /**** inline edition ****/
+function loadInlineEditionForm(eid, rtype, role, divid, reload, vid,
+                               default_value, lzone) {
+  var args = {fname: 'reledit_form', rtype: rtype, role: role, eid: eid, divid: divid,
+              reload: reload, vid: vid, default_value: default_value, landing_zone: lzone,
+              callback: function () {showInlineEditionForm(eid, rtype, divid);}};
+  jQuery('#'+divid+'-reledit').parent().loadxhtml(JSON_BASE_URL, args, 'post');
+}
+
 function showInlineEditionForm(eid, rtype, divid) {
     jQuery('#' + divid).hide();
-    jQuery('#' + divid+'-form').show();
+    jQuery('#' + divid + '-value' ).hide();
+    jQuery('#' + divid+ '-form').show();
 }
 
 function hideInlineEdit(eid, rtype, divid) {
     jQuery('#appMsg').hide();
     jQuery('div.errorMessage').remove();
     jQuery('#' + divid).show();
-    jQuery('#' + divid+'-form').hide();
+    jQuery('#' + divid + '-value').show();
+    jQuery('#' + divid +'-form').hide();
 }
 
 CubicWeb.provide('edition.js');
--- a/web/data/cubicweb.form.css	Mon Oct 19 20:22:01 2009 +0200
+++ b/web/data/cubicweb.form.css	Wed Oct 21 17:32:20 2009 +0200
@@ -180,14 +180,11 @@
   margin-left: 2em;
 }
 
-/*FIXME inlineedit not used ?*/
-/*
-div.inlineedit {
-  display: none;
+div.editableField {
+  display: inline;
 }
-*/
 
-div.editableField {
+div.editableFieldValue {
   display: inline;
 }
 
--- a/web/test/unittest_form.py	Mon Oct 19 20:22:01 2009 +0200
+++ b/web/test/unittest_form.py	Wed Oct 21 17:32:20 2009 +0200
@@ -103,7 +103,7 @@
 
     def test_reledit_composite_field(self):
         rset = self.execute('INSERT BlogEntry X: X title "cubicweb.org", X content "hop"')
-        form = self.vreg['views'].select('reledit', self.request(),
+        form = self.vreg['views'].select('doreledit', self.request(),
                                          rset=rset, row=0, rtype='content')
         data = form.render(row=0, rtype='content')
         self.failUnless('edits-content' in data)
--- a/web/test/unittest_views_basecontrollers.py	Mon Oct 19 20:22:01 2009 +0200
+++ b/web/test/unittest_views_basecontrollers.py	Wed Oct 21 17:32:20 2009 +0200
@@ -583,23 +583,6 @@
         self.assertEquals(self.execute('Any N WHERE T tags P, P is CWUser, T name N').rows,
                           [['javascript']])
 
-    def test_edit_field(self):
-        nbusers = len(self.execute('CWUser P'))
-        eid = self.john.eid
-        self.remote_call('edit_field', 'apply',
-                         ('eid', 'firstname:%s' % eid, '__maineid', '__type:%s'% eid, 'edits-firstname:%s' % eid ),
-                         (str(eid), u'Remi', str(eid), 'CWUser', self.john.firstname),
-                         'firstname',
-                         eid, 'default_value')
-        self.commit()
-        rset = self.execute('CWUser P')
-        # make sure we did not insert a new cwuser here
-        self.assertEquals(len(rset), nbusers)
-        john = self.execute('Any X WHERE X eid %(x)s', {'x': self.john.eid}, 'x').get_entity(0, 0)
-        self.assertEquals(john.eid, self.john.eid)
-        self.assertEquals(john.firstname, 'Remi')
-
-
     def test_pending_insertion(self):
         res, req = self.remote_call('add_pending_inserts', [['12', 'tags', '13']])
         deletes = req.get_pending_deletes()
--- a/web/test/unittest_views_baseviews.py	Mon Oct 19 20:22:01 2009 +0200
+++ b/web/test/unittest_views_baseviews.py	Wed Oct 21 17:32:20 2009 +0200
@@ -99,7 +99,7 @@
 
     def test_sortvalue(self):
         e, _, view = self._prepare_entity()
-        expected = ['<toto>', 'loo"ong blabla'[:10], e.creation_date.strftime('%Y-%m-%d %H:%M')]
+        expected = ['<toto>', 'loo"ong blabla'[:10], e.creation_date.strftime('%Y/%m/%d %H:%M:%S')]
         got = [loadjson(view.sortvalue(0, i)) for i in xrange(3)]
         self.assertListEqual(got, expected)
         # XXX sqlite does not handle Interval correctly
@@ -111,7 +111,7 @@
         labels = view.columns_labels()
         table = TableWidget(view)
         table.columns = view.get_columns(labels, [1, 2], None, None, None, None, 0)
-        expected = ['loo"ong blabla'[:10], e.creation_date.strftime('%Y-%m-%d %H:%M')]
+        expected = ['loo"ong blabla'[:10], e.creation_date.strftime('%Y/%m/%d %H:%M:%S')]
         got = [loadjson(value) for _, value in table.itercols(0)]
         self.assertListEqual(got, expected)
 
--- a/web/test/unittest_views_editforms.py	Mon Oct 19 20:22:01 2009 +0200
+++ b/web/test/unittest_views_editforms.py	Wed Oct 21 17:32:20 2009 +0200
@@ -45,10 +45,10 @@
                                ])
         self.assertListEquals(rbc(e, 'metadata'),
                               [('last_login_time', 'subject'),
+                               ('modification_date', 'subject'),
                                ('created_by', 'subject'),
                                ('creation_date', 'subject'),
                                ('cwuri', 'subject'),
-                               ('modification_date', 'subject'),
                                ('owned_by', 'subject'),
                                ('bookmarked_by', 'object'),
                                ])
@@ -62,10 +62,10 @@
         self.assertListEquals(rbc(e, 'generated'),
                               [('use_email', 'subject'),
                                ('in_state', 'subject'),
+                               ('is', 'subject'),
+                               ('is_instance_of', 'subject'),
                                ('has_text', 'subject'),
                                ('identity', 'subject'),
-                               ('is', 'subject'),
-                               ('is_instance_of', 'subject'),
                                ('tags', 'object'),
                                ('for_user', 'object'),
                                ('created_by', 'object'),
@@ -99,10 +99,10 @@
                                ('salary', 'subject')
                                ])
         self.assertListEquals(rbc(e, 'metadata'),
-                              [('created_by', 'subject'),
-                               ('creation_date', 'subject'),
+                              [('creation_date', 'subject'),
                                ('cwuri', 'subject'),
                                ('modification_date', 'subject'),
+                               ('created_by', 'subject'),
                                ('owned_by', 'subject'),
                                ])
         self.assertListEquals(rbc(e, 'generic'),
@@ -110,9 +110,9 @@
                                ('connait', 'object')
                                ])
         self.assertListEquals(rbc(e, 'generated'),
-                              [('has_text', 'subject'),
+                              [('is', 'subject'),
+                               ('has_text', 'subject'),
                                ('identity', 'subject'),
-                               ('is', 'subject'),
                                ('is_instance_of', 'subject'),
                                ('identity', 'object'),
                                ])
--- a/web/views/basecontrollers.py	Mon Oct 19 20:22:01 2009 +0200
+++ b/web/views/basecontrollers.py	Wed Oct 21 17:32:20 2009 +0200
@@ -397,26 +397,15 @@
         self._cw.form = self._rebuild_posted_form(names, values, action)
         return _validate_form(self._cw, self._cw.vreg)
 
-    @jsonize
-    def js_edit_field(self, action, names, values, rtype, eid, default):
-        success, args, _ = self.validate_form(action, names, values)
-        if success:
-            # Any X,N where we don't seem to use N is an optimisation
-            # printable_value won't need to query N again
-            rset = self._cw.execute('Any X,N WHERE X eid %%(x)s, X %s N' % rtype,
-                                    {'x': eid}, 'x')
-            entity = rset.get_entity(0, 0)
-            value = entity.printable_value(rtype) or default
-            return (success, args, value)
-        else:
-            return (success, args, None)
-
-    @jsonize
-    def js_reledit_form(self, eid, rtype, role, default, lzone):
-        """XXX we should get rid of this and use loadxhtml"""
-        entity = self._cw.entity_from_eid(eid)
-        return entity.view('reledit', rtype=rtype, role=role,
-                           default=default, landing_zone=lzone)
+    @xhtmlize
+    def js_reledit_form(self):
+        args = dict((x,self._cw.form[x])
+                    for x in frozenset(('rtype', 'role', 'reload', 'landing_zone')))
+        entity = self._cw.entity_from_eid(int(self._cw.form['eid']))
+        # note: default is reserved in js land
+        args['default'] = self._cw.form['default_value']
+        args['reload'] = simplejson.loads(args['reload'])
+        return entity.view('doreledit', **args)
 
     @jsonize
     def js_i18n(self, msgids):
--- a/web/views/editforms.py	Mon Oct 19 20:22:01 2009 +0200
+++ b/web/views/editforms.py	Wed Oct 21 17:32:20 2009 +0200
@@ -19,10 +19,9 @@
 from cubicweb import neg_role
 from cubicweb.selectors import (match_kwargs, one_line_rset, non_final_entity,
                                 specified_etype_implements, yes)
-from cubicweb.utils import make_uid
 from cubicweb.view import EntityView
 from cubicweb.common import tags
-from cubicweb.web import INTERNAL_FIELD_VALUE, RequestError, stdmsgs, eid_param
+from cubicweb.web import stdmsgs, eid_param
 from cubicweb.web import uicfg
 from cubicweb.web.form import FormViewMixIn, FieldNotFound
 from cubicweb.web.formfields import guess_field
@@ -111,14 +110,103 @@
     # FIXME editableField class could be toggleable from userprefs
 
     _onclick = u"showInlineEditionForm(%(eid)s, '%(rtype)s', '%(divid)s')"
-    _defaultlandingzone = (u'<img title="%(msg)s" '
-                           'src="data/accessories-text-editor.png" '
+    _onsubmit = ("return inlineValidateRelationForm('%(rtype)s', '%(role)s', '%(eid)s', "
+                 "'%(divid)s', %(reload)s, '%(vid)s', '%(default)s', '%(lzone)s');")
+    _cancelclick = "hideInlineEdit(%s,\'%s\',\'%s\')"
+    _defaultlandingzone = (u'<img title="%(msg)s" src="data/file.gif" '
                            'alt="%(msg)s"/>')
     _landingzonemsg = _('click to edit this field')
     # default relation vids according to cardinality
     _one_rvid = 'incontext'
     _many_rvid = 'csv'
 
+
+    def cell_call(self, row, col, rtype=None, role='subject',
+                  reload=False,      # controls reloading the whole page after change
+                  rvid=None,         # vid to be applied to other side of rtype (non final relations only)
+                  default=None,      # default value
+                  landing_zone=None  # prepend value with a separate html element to click onto
+                                     # (esp. needed when values are links)
+                  ):
+        """display field to edit entity's `rtype` relation on click"""
+        assert rtype
+        assert role in ('subject', 'object'), '%s is not an acceptable role value' % role
+        self.req.add_js('cubicweb.edition.js')
+        self.req.add_css('cubicweb.form.css')
+        if default is None:
+            default = xml_escape(self._cw._('<no value>'))
+        schema = self._cw.vreg.schema
+        entity = self.cw_rset.get_entity(row, col)
+        rschema = schema.rschema(rtype)
+        lzone = self._build_landing_zone(landing_zone)
+        # compute value, checking perms, build form
+        if rschema.final:
+            form = self._build_form(entity, rtype, role, 'edition', default, reload, lzone)
+            if not self.should_edit_attribute(entity, rschema, role, form):
+                self.w(entity.printable_value(rtype))
+                return
+            value = entity.printable_value(rtype) or default
+            self.relation_form(lzone, value, form,
+                               self._build_renderer(entity, rtype, role))
+        else:
+            if rvid is None:
+                rvid = self._compute_best_vid(entity.e_schema, rschema, role)
+            rset = entity.related(rtype, role)
+            if rset:
+                value = self._cw.view(rvid, rset)
+            else:
+                value = default
+            if not self.should_edit_relation(entity, rschema, role, rvid):
+                if rset:
+                    self.w(value)
+                return
+            form = self._build_form(entity, rtype, role, 'base', default, reload, lzone,
+                                    dict(vid=rvid, lzone=lzone))
+            field = guess_field(entity.e_schema, entity.schema.rschema(rtype), role)
+            form.append_field(field)
+            self.relation_form(lzone, value, form,
+                               self._build_renderer(entity, rtype, role))
+
+    def should_edit_attribute(self, entity, rschema, role, form):
+        rtype = str(rschema)
+        ttype = rschema.targets(entity.id, role)[0]
+        afs = uicfg.autoform_section.etype_get(entity.id, rtype, role, ttype)
+        if 'main_hidden' in afs or not entity.has_perm('update'):
+            return False
+        try:
+            form.field_by_name(rtype, role)
+        except FieldNotFound:
+            return False
+        return True
+
+    def should_edit_relation(self, entity, rschema, role, rvid):
+        if ((role == 'subject' and not rschema.has_perm(self._cw, 'add',
+                                                        fromeid=entity.eid))
+            or
+            (role == 'object' and not rschema.has_perm(self._cw, 'add',
+                                                       toeid=entity.eid))):
+            return False
+        return True
+
+    def relation_form(self, lzone, value, form, renderer):
+        """xxx-reledit div (class=field)
+              +-xxx div (class="editableField")
+              |   +-landing zone
+              +-xxx-value div
+              +-xxx-form div
+        """
+        w = self.w
+        divid = form.event_args['divid']
+        w(u'<div id="%s-reledit" class="field">' % form.event_args['divid'])
+        w(u'<div id="%s" class="editableField" onclick="%s" title="%s">' % (
+                divid, xml_escape(self._onclick % form.event_args),
+                self.req._(self._landingzonemsg)))
+        w(lzone)
+        w(u'</div>')
+        w(u'<div id="%s-value" class="editableFieldValue">%s</div>' % (divid, value))
+        w(form.form_render(renderer=renderer))
+        w(u'</div>')
+
     def _compute_best_vid(self, eschema, rschema, role):
         if eschema.cardinality(rschema, role) in '+*':
             return self._many_rvid
@@ -134,139 +222,45 @@
             display_help=False, table_class='',
             button_bar_class='buttonbar', display_progress_div=False)
 
-    def _build_form(self, entity, rtype, role, default, onsubmit, reload,
-                  extradata=None, **formargs):
-        divid = 'd%s' % make_uid('%s-%s' % (rtype, entity.eid))
-        event_data = {'divid' : divid, 'eid' : entity.eid, 'rtype' : rtype,
-                      'reload' : dumps(reload), 'default' : default}
+    def _build_args(self, entity, rtype, role, formid, default, reload, lzone,
+                    extradata=None):
+        divid = '%s-%s-%s' % (rtype, role, entity.eid)
+        event_args = {'divid' : divid, 'eid' : entity.eid, 'rtype' : rtype,
+                      'reload' : dumps(reload), 'default' : default, 'role' : role, 'vid' : u'',
+                      'lzone' : lzone}
         if extradata:
-            event_data.update(extradata)
-        onsubmit %= event_data
-        cancelclick = "hideInlineEdit(%s,\'%s\',\'%s\')" % (entity.eid, rtype,
-                                                            divid)
+            event_args.update(extradata)
+        return divid, event_args
+
+    def _build_form(self, entity, rtype, role, formid, default, reload, lzone,
+                  extradata=None, **formargs):
+        divid, event_args = self._build_args(entity, rtype, role, formid, default,
+                                      reload, lzone, extradata)
+        onsubmit = self._onsubmit % event_args
+        cancelclick = self._cancelclick % (entity.eid, rtype, divid)
         form = self._cw.vreg['forms'].select(
-            'edition', self._cw, entity=entity, domid='%s-form' % divid,
+            formid, self._cw, entity=entity, domid='%s-form' % divid,
             cssstyle='display: none', onsubmit=onsubmit, action='#',
-            display_fields=[(rtype, role)],
             form_buttons=[SubmitButton(), Button(stdmsgs.BUTTON_CANCEL,
                                                  onclick=cancelclick)],
             **formargs)
-        form.event_data = event_data
+        form.event_args = event_args
         return form
 
-    def cell_call(self, row, col, rtype=None, role='subject',
-                  reload=False,      # controls reloading the whole page after change
-                  rvid=None,         # vid to be applied to other side of rtype (non final relations only)
-                  default=None,      # default value
-                  landing_zone=None  # prepend value with a separate html element to click onto
-                                     # (esp. needed when values are links)
-                  ):
-        """display field to edit entity's `rtype` relation on click"""
-        assert rtype
-        assert role in ('subject', 'object')
-        if default is None:
-            default = xml_escape(self._cw._('<no value>'))
-        schema = self._cw.vreg.schema
-        entity = self.cw_rset.get_entity(row, col)
-        rschema = schema.rschema(rtype)
-        lzone = self._build_landing_zone(landing_zone)
-        # compute value, checking perms, build form
-        if rschema.final:
-            onsubmit = ("return inlineValidateAttributeForm('%(rtype)s', '%(eid)s', '%(divid)s', "
-                        "%(reload)s, '%(default)s');")
-            form = self._build_form(
-                entity, rtype, role, default, onsubmit, reload)
-            if not self.should_edit_attribute(entity, rschema, role, form):
-                self.w(entity.printable_value(rtype))
-                return
-            value = entity.printable_value(rtype) or default
-            self.attribute_form(lzone, value, form,
-                                 self._build_renderer(entity, rtype, role))
-        else:
-            if rvid is None:
-                rvid = self._compute_best_vid(entity.e_schema, rschema, role)
-            rset = entity.related(rtype, role)
-            if rset:
-                value = self._cw.view(rvid, rset)
-            else:
-                value = default
-            if not self.should_edit_relation(entity, rschema, role, rvid):
-                if rset:
-                    self.w(value)
-                return
-            onsubmit = ("return inlineValidateRelationForm('%(rtype)s', '%(role)s', '%(eid)s', "
-                        "'%(divid)s', %(reload)s, '%(vid)s', '%(default)s', '%(lzone)s');")
-            form = self._build_form(
-                entity, rtype, role, default, onsubmit, reload,
-                dict(vid=rvid, role=role, lzone=lzone))
-            self.relation_form(lzone, value, form,
-                               self._build_renderer(entity, rtype, role))
-
-    def should_edit_attribute(self, entity, rschema, role, form):
-        rtype = str(rschema)
-        ttype = rschema.targets(entity.__regid__, role)[0]
-        afs = uicfg.autoform_section.etype_get(entity.__regid__, rtype, role, ttype)
-        if 'main_hidden' in afs or not entity.has_perm('update'):
-            self.w(entity.printable_value(rtype))
-            return False
-        try:
-            field = form.field_by_name(rtype, role)
-        except FieldNotFound:
-            self.w(entity.printable_value(rtype))
-            return False
-        return True
-
-    def should_edit_relation(self, entity, rschema, role, rvid):
-        if ((role == 'subject' and not rschema.has_perm(self._cw, 'add',
-                                                        fromeid=entity.eid))
-            or
-            (role == 'object' and not rschema.has_perm(self._cw, 'add',
-                                                       toeid=entity.eid))):
-            self.wview(rvid, entity.related(str(rschema), role), 'null')
-            return False
-        return True
-
-    def attribute_form(self, lzone, value, form, renderer):
-        """div (class=field)
-              +-xxx div
-              |  +-xxx div (class=editableField)
-              |  |  +-landing zone
-              |  +-value-xxx div
-              |     +-value
-              +-form-xxx div
-        """
-        w = self.w
-        w(u'<div class="field">')
-        w(u'<div id="%s" style="display: inline">' % form.event_data['divid'])
-        w(tags.div(lzone, klass='editableField',
-                   onclick=self._onclick % form.event_data))
-        w(u'<div id="value-%s" style="display: inline">%s</div>' %
-               (form.event_data['divid'], value))
-        w(u'</div>')
-        w(form.form_render(renderer=renderer))
-        w(u'</div>')
-
-    def relation_form(self, lzone, value, form, renderer):
-        """xxx-reledit div (class=field)
-              +-xxx div (class="editableField")
-              |   +-landing zone
-              +-value
-              +-form-xxx div
-        """
-        w = self.w
-        w(u'<div id="%s-reledit" class="field">' % form.event_data['divid'])
-        w(tags.div(lzone, klass='editableField', id=form.event_data['divid'],
-                   onclick=self._onclick % form.event_data))
-        w(value)
-        w(form.form_render(renderer=renderer))
-        w(u'</div>')
-
+class DummyForm(object):
+    __slots__ = ('event_args',)
+    def form_render(self, **_args):
+        return u''
+    def append_field(self, *args):
+        pass
 
 class AutoClickAndEditFormView(ClickAndEditFormView):
     """same as ClickAndEditFormView but checking if the view *should* be applied
     by checking uicfg configuration and composite relation property.
     """
     __regid__ = 'reledit'
+    _onclick = (u"loadInlineEditionForm(%(eid)s, '%(rtype)s', '%(role)s', "
+                "'%(divid)s', %(reload)s, '%(vid)s', '%(default)s', '%(lzone)s');")
 
     def should_edit_relation(self, entity, rschema, role, rvid):
         eschema = entity.e_schema
@@ -283,6 +277,16 @@
         return super(AutoClickAndEditFormView, self).should_edit_relation(
             entity, rschema, role, rvid)
 
+    def _build_form(self, entity, rtype, role, formid, default, reload, lzone,
+                  extradata=None, **formargs):
+        _divid, event_args = self._build_args(entity, rtype, role, formid, default,
+                                              reload, lzone, extradata)
+        form = DummyForm()
+        form.event_args = event_args
+        return form
+
+    def _build_renderer(self, entity, rtype, role):
+        pass
 
 class EditionFormView(FormViewMixIn, EntityView):
     """display primary entity edition form"""
--- a/web/views/navigation.py	Mon Oct 19 20:22:01 2009 +0200
+++ b/web/views/navigation.py	Wed Oct 21 17:32:20 2009 +0200
@@ -62,6 +62,8 @@
         req = self._cw
         if attrname is not None:
             def index_display(row):
+                if not rset[row][col]: # outer join
+                    return u''
                 entity = rset.get_entity(row, col)
                 return entity.printable_value(attrname, format='text/plain')
         elif self._cw.schema.eschema(rset.description[0][col]).final:
--- a/web/views/schema.py	Mon Oct 19 20:22:01 2009 +0200
+++ b/web/views/schema.py	Wed Oct 21 17:32:20 2009 +0200
@@ -18,7 +18,7 @@
 from cubicweb.schemaviewer import SchemaViewer
 from cubicweb.view import EntityView, StartupView
 from cubicweb.common import tags, uilib
-from cubicweb.web import action, facet
+from cubicweb.web import action, facet, uicfg
 from cubicweb.web.views import TmpFileViewMixin
 from cubicweb.web.views import primary, baseviews, tabs, management
 
@@ -36,6 +36,11 @@
         return SKIP_TYPES
     return ALWAYS_SKIP_TYPES
 
+_pvs = uicfg.primaryview_section
+for _action in ('read', 'add', 'update', 'delete'):
+    _pvs.tag_subject_of(('*', '%s_permission' % _action, '*'), 'hidden')
+    _pvs.tag_object_of(('*', '%s_permission' % _action, '*'), 'hidden')
+
 # global schema view ###########################################################
 
 class SchemaView(tabs.TabsMixin, StartupView):
@@ -279,6 +284,7 @@
 
     def cell_call(self, row, col):
         entity = self.cw_rset.get_entity(row, col)
+        _ = self._cw._
         self.w(u'<h2>%s</h2>' % _('Add permissions'))
         rset = self._cw.execute('Any P WHERE X add_permission P, '
                                 'X eid %(x)s',
@@ -335,7 +341,7 @@
         super(CWRTypeSchemaView, self).render_entity_attributes(entity)
         rschema = self._cw.vreg.schema.rschema(entity.name)
         viewer = SchemaViewer(self._cw)
-        layout = viewer.visit_relationschema(rschema)
+        layout = viewer.visit_relationschema(rschema, title=False)
         self.w(uilib.ureport_as_html(layout))
         if not rschema.final:
             msg = self._cw._('graphical schema for %s') % entity.name