Ledgers and inventory: movement facts and balanced postings
Overview
A stock movement stores a signed quantity change rather than only the current total. A journal entry groups financial postings; in this simplified single-currency ledger signed integer cents must sum to zero per entry, with positive and negative signs standing for debits and credits. The stock fixture uses receipts and issues, and the financial fixture has two balanced entries. These are teaching models, not accounting software.
First example
SELECT i.id,COALESCE(SUM(m.delta),0) AS balanceFROM pro_item i LEFT JOIN pro_move m ON m.tenant_id=i.tenant_id AND m.item_id=i.idGROUP BY i.id ORDER BY i.id;Observed SQLite result (rows in JSON):
[ [ 101, 7 ], [ 102, 0 ], [ 201, 5 ]]How it works
Example 1 calculates balances including zero for items with no movements; example 2 checks every journal entry, counting postings and detecting an empty or unbalanced entry. A row CHECK cannot ensure a multi-row entry balances. In production validate the complete posting group atomically, distinguish draft from posted entries, prevent unauthorized edits, and use compensating postings rather than altering history. Unique event identifiers aid idempotency but replay logic must compare intent. Preventing overselling requires concurrency-safe reservation or conditional updates, not just reading SUM before writing. Integer cents avoid binary floating-point rounding; currencies and units must not be mixed.
Practical example
SELECT e.id,COUNT(p.line_no) AS lines,COALESCE(SUM(p.cents),0) AS netFROM pro_entry e LEFT JOIN pro_posting p ON p.entry_id=e.idGROUP BY e.id HAVING COUNT(p.line_no)<2 OR COALESCE(SUM(p.cents),0)<>0ORDER BY e.id;Observed SQLite result (rows in JSON):
[]Practice and mistakes
Practice: add a new empty journal entry to a disposable database and rerun the diagnostic. Then add only one posting and observe a nonzero balance. Explain why a balanced entry is necessary but not sufficient for correct accounting.