000005_holds.up.sql32 lines, 1.2 KB
| 1 | BEGIN; |
| 2 | |
| 3 | -- Money set aside for a transfer saga, until it's captured or released. |
| 4 | CREATE TYPE hold_status AS ENUM ('held', 'captured', 'released'); |
| 5 | |
| 6 | CREATE TABLE holds ( |
| 7 | -- chosen by the caller: the idempotency key |
| 8 | id uuid PRIMARY KEY, |
| 9 | wallet_id uuid NOT NULL REFERENCES accounts (id), |
| 10 | amount bigint NOT NULL CHECK (amount > 0), |
| 11 | currency text NOT NULL, |
| 12 | status hold_status NOT NULL DEFAULT 'held', |
| 13 | hold_tx_id uuid NOT NULL REFERENCES transactions (id), |
| 14 | -- where the money went in the end |
| 15 | settled_to uuid REFERENCES accounts (id), |
| 16 | settle_tx_id uuid REFERENCES transactions (id), |
| 17 | created_at timestamptz NOT NULL DEFAULT now(), |
| 18 | settled_at timestamptz, |
| 19 | CHECK ((status = 'held') = (settle_tx_id IS NULL)) |
| 20 | ); |
| 21 | |
| 22 | -- Held money waits in a system account, one per currency. |
| 23 | INSERT INTO accounts (kind, name, currency, normal_balance) VALUES |
| 24 | ('system', 'holds', 'EUR', 'credit'), |
| 25 | ('system', 'holds', 'GBP', 'credit'), |
| 26 | ('system', 'holds', 'JPY', 'credit'), |
| 27 | ('system', 'holds', 'USD', 'credit'); |
| 28 | |
| 29 | -- A frozen wallet can't send or receive money. |
| 30 | ALTER TABLE accounts ADD COLUMN frozen boolean NOT NULL DEFAULT false; |
| 31 | |
| 32 | COMMIT; |