000002_wallets.up.sql37 lines, 1.7 KB
| 1 | BEGIN; |
| 2 | |
| 3 | -- A wallet belongs to a customer. A system account belongs to us: money |
| 4 | -- enters and leaves the ledger through system accounts. |
| 5 | CREATE TYPE account_kind AS ENUM ('wallet', 'system'); |
| 6 | |
| 7 | -- Existing accounts without an owner become system accounts. |
| 8 | ALTER TABLE accounts ADD COLUMN kind account_kind NOT NULL DEFAULT 'wallet'; |
| 9 | UPDATE accounts SET kind = 'system' WHERE owner_id IS NULL; |
| 10 | ALTER TABLE accounts ALTER COLUMN kind DROP DEFAULT; |
| 11 | |
| 12 | -- Wallets always have an owner, and system accounts never do. |
| 13 | ALTER TABLE accounts ADD CONSTRAINT accounts_kind_owner_check |
| 14 | CHECK ((kind = 'wallet') = (owner_id IS NOT NULL)); |
| 15 | |
| 16 | -- One wallet per owner and currency, and one system account per name and |
| 17 | -- currency, so code can look a system account up by its name. |
| 18 | CREATE UNIQUE INDEX accounts_wallet_owner_currency_idx |
| 19 | ON accounts (owner_id, currency) WHERE kind = 'wallet'; |
| 20 | CREATE UNIQUE INDEX accounts_system_name_currency_idx |
| 21 | ON accounts (name, currency) WHERE kind = 'system'; |
| 22 | |
| 23 | -- Deposits are funded from a settlement account: the money we hold at our |
| 24 | -- bank. One per supported currency; a new currency is a new migration. |
| 25 | INSERT INTO accounts (kind, name, currency, normal_balance) VALUES |
| 26 | ('system', 'settlement', 'EUR', 'debit'), |
| 27 | ('system', 'settlement', 'GBP', 'debit'), |
| 28 | ('system', 'settlement', 'JPY', 'debit'), |
| 29 | ('system', 'settlement', 'USD', 'debit') |
| 30 | ON CONFLICT (name, currency) WHERE kind = 'system' DO NOTHING; |
| 31 | |
| 32 | -- Listing a wallet's entries reads them in id order. This index serves that |
| 33 | -- directly, and replaces the index on account_id alone. |
| 34 | CREATE INDEX entries_account_id_id_idx ON entries (account_id, id); |
| 35 | DROP INDEX entries_account_id_idx; |
| 36 | |
| 37 | COMMIT; |