'If an account that receives money is taken over during payin we need
to transfer the balance to the absorbing account.'

def take_over_balances(self):

    log(u'Taking    over    balances.')
    for i in itertools.count():
        if (i > 10):
            raise Exception(u'possible    infinite    loop')
        count = self.db.one(u'\n\n                                                                DROP    TABLE    IF    EXISTS    temp;\n                                                                CREATE    TEMPORARY    TABLE    temp    AS\n                                                                                SELECT    archived_as,    absorbed_by,    balance    AS    archived_balance\n                                                                                        FROM    absorptions    a\n                                                                                        JOIN    participants    p    ON    a.archived_as    =    p.username\n                                                                                    WHERE    balance    >    0;\n\n                                                                SELECT    count(*)    FROM    temp;\n\n                                                ')
        if (not count):
            break
        self.db.run(u"\n\n                                                                INSERT    INTO    transfers    (tipper,    tippee,    amount,    context)\n                                                                                SELECT    archived_as,    absorbed_by,    archived_balance,    'take-over'\n                                                                                        FROM    temp;\n\n                                                                UPDATE    participants\n                                                                            SET    balance    =    (balance    -    archived_balance)\n                                                                        FROM    temp\n                                                                    WHERE    username    =    archived_as;\n\n                                                                UPDATE    participants\n                                                                            SET    balance    =    (balance    +    archived_balance)\n                                                                        FROM    temp\n                                                                    WHERE    username    =    absorbed_by;\n\n                                                ")
