000001_init_ledger.up.sql118 lines, 4.0 KB
| 1 | BEGIN; |
| 2 | |
| 3 | -- Debit or credit: the two sides of every entry. |
| 4 | CREATE TYPE entry_direction AS ENUM ('debit', 'credit'); |
| 5 | |
| 6 | -- An account is anything that holds money: a user's wallet, or a |
| 7 | -- system account, like the bank account that deposits come from. |
| 8 | CREATE TABLE accounts ( |
| 9 | id uuid PRIMARY KEY DEFAULT gen_random_uuid(), |
| 10 | -- the user from the auth service; NULL for system accounts |
| 11 | owner_id uuid, |
| 12 | name text NOT NULL CHECK (name <> ''), |
| 13 | currency text NOT NULL CHECK (currency ~ '^[A-Z]{3}$'), |
| 14 | normal_balance entry_direction NOT NULL, |
| 15 | created_at timestamptz NOT NULL DEFAULT now(), |
| 16 | UNIQUE (id, currency) |
| 17 | ); |
| 18 | |
| 19 | CREATE INDEX accounts_owner_id_idx ON accounts (owner_id); |
| 20 | |
| 21 | -- The journal: one row per movement of money. |
| 22 | CREATE TABLE transactions ( |
| 23 | id uuid PRIMARY KEY DEFAULT gen_random_uuid(), |
| 24 | description text NOT NULL, |
| 25 | created_at timestamptz NOT NULL DEFAULT now() |
| 26 | ); |
| 27 | |
| 28 | -- One line of a transaction: an amount debited or credited to an account. |
| 29 | CREATE TABLE entries ( |
| 30 | id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, |
| 31 | transaction_id uuid NOT NULL REFERENCES transactions (id), |
| 32 | account_id uuid NOT NULL, |
| 33 | direction entry_direction NOT NULL, |
| 34 | amount bigint NOT NULL CHECK (amount > 0), |
| 35 | currency text NOT NULL, |
| 36 | created_at timestamptz NOT NULL DEFAULT now(), |
| 37 | -- an entry's currency must match its account's currency |
| 38 | FOREIGN KEY (account_id, currency) REFERENCES accounts (id, currency) |
| 39 | ); |
| 40 | |
| 41 | -- Postgres does not index foreign keys for us. |
| 42 | CREATE INDEX entries_transaction_id_idx ON entries (transaction_id); |
| 43 | CREATE INDEX entries_account_id_idx ON entries (account_id); |
| 44 | |
| 45 | -- A transaction must have entries, and its debits must equal its credits |
| 46 | -- in every currency. Checked at COMMIT, once all the entries exist. |
| 47 | CREATE FUNCTION check_transaction_balanced() RETURNS trigger |
| 48 | LANGUAGE plpgsql AS $$ |
| 49 | DECLARE |
| 50 | tx_id uuid; |
| 51 | BEGIN |
| 52 | IF TG_TABLE_NAME = 'transactions' THEN |
| 53 | tx_id := NEW.id; |
| 54 | ELSE |
| 55 | tx_id := NEW.transaction_id; |
| 56 | END IF; |
| 57 | |
| 58 | IF NOT EXISTS (SELECT 1 FROM entries WHERE transaction_id = tx_id) THEN |
| 59 | RAISE EXCEPTION 'transaction % has no entries', tx_id |
| 60 | USING ERRCODE = 'check_violation'; |
| 61 | END IF; |
| 62 | |
| 63 | IF EXISTS ( |
| 64 | SELECT 1 |
| 65 | FROM entries |
| 66 | WHERE transaction_id = tx_id |
| 67 | GROUP BY currency |
| 68 | HAVING sum(CASE direction WHEN 'debit' THEN amount ELSE -amount END) <> 0 |
| 69 | ) THEN |
| 70 | RAISE EXCEPTION 'transaction % is not balanced', tx_id |
| 71 | USING ERRCODE = 'check_violation'; |
| 72 | END IF; |
| 73 | |
| 74 | RETURN NULL; |
| 75 | END; |
| 76 | $$; |
| 77 | |
| 78 | CREATE CONSTRAINT TRIGGER transactions_balanced |
| 79 | AFTER INSERT ON transactions |
| 80 | DEFERRABLE INITIALLY DEFERRED |
| 81 | FOR EACH ROW EXECUTE FUNCTION check_transaction_balanced(); |
| 82 | |
| 83 | CREATE CONSTRAINT TRIGGER entries_balanced |
| 84 | AFTER INSERT ON entries |
| 85 | DEFERRABLE INITIALLY DEFERRED |
| 86 | FOR EACH ROW EXECUTE FUNCTION check_transaction_balanced(); |
| 87 | |
| 88 | -- The ledger is append-only: mistakes are fixed with a reversing transaction. |
| 89 | CREATE FUNCTION forbid_ledger_changes() RETURNS trigger |
| 90 | LANGUAGE plpgsql AS $$ |
| 91 | BEGIN |
| 92 | RAISE EXCEPTION '% is append-only, post a reversing transaction instead', TG_TABLE_NAME |
| 93 | USING ERRCODE = 'restrict_violation'; |
| 94 | END; |
| 95 | $$; |
| 96 | |
| 97 | CREATE TRIGGER transactions_append_only |
| 98 | BEFORE UPDATE OR DELETE ON transactions |
| 99 | FOR EACH ROW EXECUTE FUNCTION forbid_ledger_changes(); |
| 100 | |
| 101 | CREATE TRIGGER entries_append_only |
| 102 | BEFORE UPDATE OR DELETE ON entries |
| 103 | FOR EACH ROW EXECUTE FUNCTION forbid_ledger_changes(); |
| 104 | |
| 105 | -- Balances are derived from entries, never stored. |
| 106 | CREATE VIEW account_balances AS |
| 107 | SELECT |
| 108 | a.id AS account_id, |
| 109 | a.name, |
| 110 | a.currency, |
| 111 | coalesce(sum( |
| 112 | CASE WHEN e.direction = a.normal_balance THEN e.amount ELSE -e.amount END |
| 113 | ), 0)::bigint AS balance |
| 114 | FROM accounts a |
| 115 | LEFT JOIN entries e ON e.account_id = a.id |
| 116 | GROUP BY a.id; |
| 117 | |
| 118 | COMMIT; |