000001_transfers.up.sql43 lines, 2.0 KB
| 1 | BEGIN; |
| 2 | |
| 3 | -- A transfer is a saga. Its row says where the saga is, at all times. |
| 4 | CREATE TABLE transfers ( |
| 5 | id uuid PRIMARY KEY DEFAULT gen_random_uuid(), |
| 6 | user_id uuid NOT NULL, |
| 7 | idempotency_key text NOT NULL, |
| 8 | from_wallet_id uuid NOT NULL, |
| 9 | to_wallet_id uuid NOT NULL CHECK (to_wallet_id <> from_wallet_id), |
| 10 | amount bigint NOT NULL CHECK (amount > 0), |
| 11 | currency text NOT NULL CHECK (currency ~ '^[A-Z]{3}$'), |
| 12 | -- a CHECK, not an enum: states come and go as the saga grows |
| 13 | state text NOT NULL DEFAULT 'pending' CHECK (state IN |
| 14 | ('pending', 'funds_held', 'completed', 'compensating', 'failed', 'reversed')), |
| 15 | failure_reason text NOT NULL DEFAULT '', |
| 16 | -- tries of the current step, and when the next one is due |
| 17 | attempts integer NOT NULL DEFAULT 0, |
| 18 | next_attempt_at timestamptz NOT NULL DEFAULT now(), |
| 19 | -- bumped by every write: optimistic concurrency |
| 20 | version integer NOT NULL DEFAULT 1, |
| 21 | created_at timestamptz NOT NULL DEFAULT now(), |
| 22 | updated_at timestamptz NOT NULL DEFAULT now(), |
| 23 | UNIQUE (user_id, idempotency_key), |
| 24 | CHECK ((state IN ('compensating', 'failed', 'reversed')) = (failure_reason <> '')) |
| 25 | ); |
| 26 | |
| 27 | -- Which unfinished transfers are due? |
| 28 | CREATE INDEX transfers_due_idx ON transfers (next_attempt_at) |
| 29 | WHERE state IN ('pending', 'funds_held', 'compensating'); |
| 30 | |
| 31 | -- Every try of every step: the saga's history. |
| 32 | CREATE TABLE transfer_steps ( |
| 33 | id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, |
| 34 | transfer_id uuid NOT NULL REFERENCES transfers (id), |
| 35 | step text NOT NULL, |
| 36 | outcome text NOT NULL CHECK (outcome IN ('succeeded', 'rejected', 'failed')), |
| 37 | detail text NOT NULL DEFAULT '', |
| 38 | created_at timestamptz NOT NULL DEFAULT now() |
| 39 | ); |
| 40 | |
| 41 | CREATE INDEX transfer_steps_transfer_id_idx ON transfer_steps (transfer_id, id); |
| 42 | |
| 43 | COMMIT; |