knaxuslearn · build · ship

Projects / Bank ledger / Phase 1

Phase 1 of 4 · about 2.5 hours

Tables that refuse bad data

You end with five bad rows, and the database refuses all five by itself.

Most data bugs start small: a blank name, a negative amount, a payment to an account that does not exist. If the application is the only guard, one forgotten check lets the bad row in forever. So we put the rules in the tables, where nothing can skip them.

Step 1.1: Accounts (about 30 minutes)

An account is a place money can sit. Create the first table:

CREATE TABLE accounts (
  id             bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  owner          text        NOT NULL CHECK (length(trim(owner)) > 0),
  currency       char(3)     NOT NULL CHECK (currency ~ '^[A-Z]{3}$'),
  allow_negative boolean     NOT NULL DEFAULT false,
  created_at     timestamptz NOT NULL DEFAULT now()
);

Four ideas are in there:

  • GENERATED ALWAYS AS IDENTITY hands out ids for us, one after another.
  • NOT NULL means the column must have a value.
  • A CHECK constraint is a rule the row must pass. The owner cannot be blank, and the currency must be three capital letters such as USD.
  • allow_negative is false for customers. Only the bank's own funding account will be allowed to go below zero, because that is where new money enters the system.

Notice we use bigint and plain cents everywhere. Money never goes into a floating point type, because 0.1 + 0.2 is not exactly 0.3 there.

Step 1.2: Transfers and entries (about 40 minutes)

Here is the central idea of a ledger. Money is never "changed" on an account. A transfer is one event, and it is made of entries: lines that say how much each account gained or lost. A $25 payment from Asha to Ben is one transfer with two entries, -2500 on Asha and +2500 on Ben. Add up every entry in the whole ledger and you always get zero.

CREATE TABLE transfers (
  id              bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  idempotency_key text        NOT NULL UNIQUE,
  memo            text,
  created_at      timestamptz NOT NULL DEFAULT now()
);

CREATE TABLE entries (
  id           bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  transfer_id  bigint      NOT NULL REFERENCES transfers (id),
  account_id   bigint      NOT NULL REFERENCES accounts (id),
  amount_cents bigint      NOT NULL CHECK (amount_cents <> 0),
  created_at   timestamptz NOT NULL DEFAULT now()
);

Two new ideas:

  • REFERENCES makes a foreign key. An entry must point at a transfer and an account that really exist.
  • The UNIQUE idempotency key lets a client say "this is payment pay-001". If the network drops and the app sends the same request twice, the second one can be recognised and ignored. We use it in Phase 2.

Check what you made. \d entries lists the columns, the check and the two foreign keys.

Step 1.3: Put in three accounts (about 20 minutes)

INSERT INTO accounts (owner, currency, allow_negative) VALUES
  ('Bank (funding source)', 'USD', true),
  ('Asha', 'USD', false),
  ('Ben',  'USD', false);

SELECT id, owner, currency, allow_negative FROM accounts ORDER BY id;
 id |         owner         | currency | allow_negative
----+-----------------------+----------+----------------
  1 | Bank (funding source) | USD      | t
  2 | Asha                  | USD      | f
  3 | Ben                   | USD      | f
(3 rows)

Step 1.4: Try to break it (about 60 minutes, take your time)

Now the fun part. Run each of these. Every one should fail.

-- 1. A blank owner
INSERT INTO accounts (owner, currency) VALUES ('   ', 'USD');

-- 2. A lowercase currency code
INSERT INTO accounts (owner, currency) VALUES ('Chen', 'usd');

-- A transfer to hang entries on
INSERT INTO transfers (idempotency_key) VALUES ('t-001');

-- 3. An entry of zero
INSERT INTO entries (transfer_id, account_id, amount_cents) VALUES (1, 2, 0);

-- 4. An account that does not exist
INSERT INTO entries (transfer_id, account_id, amount_cents) VALUES (1, 999, 500);

-- 5. A reused idempotency key
INSERT INTO transfers (idempotency_key) VALUES ('t-001');

You should see five errors, each naming the rule that stopped the row:

ERROR:  new row for relation "accounts" violates check constraint "accounts_owner_check"
ERROR:  new row for relation "accounts" violates check constraint "accounts_currency_check"
ERROR:  new row for relation "entries" violates check constraint "entries_amount_cents_check"
ERROR:  insert or update on table "entries" violates foreign key constraint "entries_account_id_fkey"
ERROR:  duplicate key value violates unique constraint "transfers_idempotency_key_key"

Each error is followed by a DETAIL line with the failing row. Read them. That is PostgreSQL telling you exactly why.

If one of the five did not fail, check the table definition from Step 1.1 and 1.2 for a typo. A missing constraint is the usual cause.

Pitfall: the two rejected accounts still used up ids 4 and 5. The next account you create will be number 6. Gaps in identity numbers are normal, and harmless.

Phase 1 done

Five bad rows went in and five errors came out. Your tables now defend themselves. Take a break: you have finished a quarter of the project.