'Rewrite any "a JOIN (b JOIN c)" expression as
"a JOIN (select * from b JOIN c) AS anon", to support
databases that can\'t parse a parenthesized join correctly
(i.e. sqlite the main one).'

def _transform_select_for_nested_joins(self, select):

    cloned = {}
    column_translate = [{}]
    def visit(element, **kw):
        if (element in column_translate[(-1)]):
            return column_translate[(-1)][element]
        elif (element in cloned):
            return cloned[element]
        newelem = cloned[element] = element._clone()
        if (newelem.is_selectable and newelem._is_join and isinstance(newelem.right, selectable.FromGrouping)):
            newelem._reset_exported()
            newelem.left = visit(newelem.left, **kw)
            right = visit(newelem.right, **kw)
            selectable_ = selectable.Select([right.element], use_labels=True).alias()
            for c in selectable_.c:
                c._key_label = c.key
                c._label = c.name
            translate_dict = dict(zip(newelem.right.element.c, selectable_.c))
            translate_dict[right.element.left] = selectable_
            translate_dict[right.element.right] = selectable_
            translate_dict[newelem.right.element.left] = selectable_
            translate_dict[newelem.right.element.right] = selectable_
            for (k, v) in list(column_translate[(-1)].items()):
                if (v in translate_dict):
                    column_translate[(-1)][k] = translate_dict[v]
            column_translate[(-1)].update(translate_dict)
            newelem.right = selectable_
            newelem.onclause = visit(newelem.onclause, **kw)
        elif (newelem.is_selectable and newelem._is_from_container):
            kw['transform_clue'] = 'select_container'
            newelem._copy_internals(clone=visit, **kw)
        elif (newelem.is_selectable and newelem._is_select):
            barrier_select = (kw.get('transform_clue', None) == 'select_container')
            if barrier_select:
                column_translate.append({})
            kw['transform_clue'] = 'inside_select'
            newelem._copy_internals(clone=visit, **kw)
            if barrier_select:
                del column_translate[(-1)]
        else:
            newelem._copy_internals(clone=visit, **kw)
        return newelem
    return visit(select)
