'Sometimes joins at the end of a multi-table sequence can be trimmed. If
the final join is against the same column as we are comparing against,
and is an inner join, we can go back one step in a join chain and
compare against the LHS of the join instead (and then repeat the
optimization). The result, potentially, involves less table joins.
The \'target\' parameter is the final field being joined to, \'join_list\'
is the full list of join aliases.
The \'last\' list contains offsets into \'join_list\', corresponding to
each component of the filter.  Many-to-many relations, for example, add
two tables to the join list and we want to deal with both tables the
same way, so \'last\' has an entry for the first of the two tables and
then the table immediately after the second table, in that case.
The \'trim\' parameter forces the final piece of the join list to be
trimmed before anything. See the documentation of add_filter() for
details about this.
Returns the final active column and table alias and the new active
join_list.'

def trim_joins(self, target, join_list, last, trim):

    final = len(join_list)
    penultimate = last.pop()
    if (penultimate == final):
        penultimate = last.pop()
    if (trim and (len(join_list) > 1)):
        extra = join_list[penultimate:]
        join_list = join_list[:penultimate]
        final = penultimate
        penultimate = last.pop()
        col = self.alias_map[extra[0]][LHS_JOIN_COL]
        for alias in extra:
            self.unref_alias(alias)
    else:
        col = target.column
    alias = join_list[(-1)]
    while (final > 1):
        join = self.alias_map[alias]
        if ((col != join[RHS_JOIN_COL]) or (join[JOIN_TYPE] != self.INNER)):
            break
        self.unref_alias(alias)
        alias = join[LHS_ALIAS]
        col = join[LHS_JOIN_COL]
        join_list = join_list[:(-1)]
        final -= 1
        if (final == penultimate):
            penultimate = last.pop()
    return (col, alias, join_list)
