@staticmethod
    def update_balances(cursor):
        log("Updating balances.")
        participants = cursor.all("""

            UPDATE participants p
               SET balance = (balance + p2.new_balance - p2.old_balance)
              FROM payday_participants p2
             WHERE p.id = p2.id
               AND p2.new_balance <> p2.old_balance
         RETURNING p.id
                 , p.username
                 , balance AS new_balance
                 , ( SELECT balance
                       FROM participants p3
                      WHERE p3.id = p.id
                   ) AS cur_balance;

        """)
        # Check that balances aren't becoming (more) negative
        for p in participants:
            if p.new_balance < 0 and p.new_balance < p.cur_balance:
                log(p)
                raise NegativeBalance()
        cursor.run("""
            INSERT INTO payments (timestamp, participant, team, amount, direction, payday)
                SELECT *, (SELECT id FROM paydays WHERE extract(year from ts_end) = 1970)
                  FROM payday_payments;
        """)

        log("Updated the balances of %i participants." % len(participants))
dataset/ETHPy150Open gratipay/gratipay.com/gratipay/billing/payday.py/Payday.update_balances/original