'Changes the aliases in change_map (which maps old-alias -> new-alias),
relabelling any references to them in select columns and the where
clause.'

def change_aliases(self, change_map):

    assert (set(change_map.keys()).intersection(set(change_map.values())) == set())
    self.where.relabel_aliases(change_map)
    self.having.relabel_aliases(change_map)
    for columns in [self.select, (self.group_by or [])]:
        for (pos, col) in enumerate(columns):
            if isinstance(col, (list, tuple)):
                old_alias = col[0]
                columns[pos] = (change_map.get(old_alias, old_alias), col[1])
            else:
                col.relabel_aliases(change_map)
    for mapping in [self.aggregates]:
        for (key, col) in mapping.items():
            if isinstance(col, (list, tuple)):
                old_alias = col[0]
                mapping[key] = (change_map.get(old_alias, old_alias), col[1])
            else:
                col.relabel_aliases(change_map)
    for (old_alias, new_alias) in change_map.iteritems():
        alias_data = list(self.alias_map[old_alias])
        alias_data[RHS_ALIAS] = new_alias
        t = self.rev_join_map[old_alias]
        data = list(self.join_map[t])
        data[data.index(old_alias)] = new_alias
        self.join_map[t] = tuple(data)
        self.rev_join_map[new_alias] = t
        del self.rev_join_map[old_alias]
        self.alias_refcount[new_alias] = self.alias_refcount[old_alias]
        del self.alias_refcount[old_alias]
        self.alias_map[new_alias] = tuple(alias_data)
        del self.alias_map[old_alias]
        table_aliases = self.table_map[alias_data[TABLE_NAME]]
        for (pos, alias) in enumerate(table_aliases):
            if (alias == old_alias):
                table_aliases[pos] = new_alias
                break
        for (pos, alias) in enumerate(self.tables):
            if (alias == old_alias):
                self.tables[pos] = new_alias
                break
    for (key, alias) in self.included_inherited_models.items():
        if (alias in change_map):
            self.included_inherited_models[key] = change_map[alias]
    for (alias, data) in self.alias_map.iteritems():
        lhs = data[LHS_ALIAS]
        if (lhs in change_map):
            data = list(data)
            data[LHS_ALIAS] = change_map[lhs]
            self.alias_map[alias] = tuple(data)
