Transactions, references and how to enforce double entry bookkeeping? (PG)
First, this is exactly the question I had in mind when I asked Modelling constraints on subset aggregates? which is certainly the place to start.  That question is more general though than this and so my answer here will have a bit more information regarding practical approaches.

You probably do not want to do this declaratively in PostgreSQL.  The only possible declarative solutions either break 1NF or are extremely complicated and so this means doing it imperatively.

In LedgerSMB we expect to do this enforcement in two stages (both of which are strict).


All journal entries will come in via stored procedures.  These stored procedures will accept a list of line items as an array and check that the sum is equal to 0.  Our model in the db is that we have a single amount column with negative numbers being debits and positive numbers being credits (if I was starting over, I would have positive numbers as debits and negative numbers as credits because this is just a little more natural but the reasons here are obscure).  Debits and credits are merged on storage and separated on retrieval by the presentation layer.  This makes running totals a lot easier.
We will use a deferred constraint trigger which will check on commit based on the system fields on the table.  This means that the lines entered in a given transaction must balance, but we can do this beyond the lines themselves.