ledger.sql55 lines, 2.1 KB
| 1 | -- name: CreateTransaction :one |
| 2 | INSERT INTO transactions (description) |
| 3 | VALUES ($1) |
| 4 | RETURNING *; |
| 5 | |
| 6 | -- name: CreateEntry :one |
| 7 | INSERT INTO entries (transaction_id, account_id, direction, amount, currency) |
| 8 | VALUES ($1, $2, $3, $4, $5) |
| 9 | RETURNING *; |
| 10 | |
| 11 | -- name: ListEntriesByAccount :many |
| 12 | -- Newest first, one page at a time: pass the last id you saw as before_id. |
| 13 | SELECT * FROM entries |
| 14 | WHERE account_id = @account_id |
| 15 | AND id < @before_id |
| 16 | ORDER BY id DESC |
| 17 | LIMIT @page_size; |
| 18 | |
| 19 | -- name: BalanceBefore :one |
| 20 | -- An account's balance from its entries before a moment: a statement's |
| 21 | -- opening balance. |
| 22 | SELECT coalesce(sum(CASE WHEN e.direction = a.normal_balance THEN e.amount ELSE -e.amount END), 0)::bigint |
| 23 | FROM entries e |
| 24 | JOIN accounts a ON a.id = e.account_id |
| 25 | WHERE e.account_id = @account_id AND e.created_at < @before; |
| 26 | |
| 27 | -- name: StatementPage :many |
| 28 | -- A page of an account's entries posted before until, oldest first, after the |
| 29 | -- entry at (after_at, after_id): keyset pagination, in the order of the index |
| 30 | -- on (account_id, created_at, id), as fast for the last page as the first. |
| 31 | -- The first page starts after (since, 0). |
| 32 | SELECT e.id, e.created_at, e.transaction_id, t.description, e.direction, e.amount |
| 33 | FROM entries e |
| 34 | JOIN transactions t ON t.id = e.transaction_id |
| 35 | WHERE e.account_id = @account_id |
| 36 | AND (e.created_at, e.id) > (@after_at::timestamptz, @after_id::bigint) |
| 37 | AND e.created_at < @until |
| 38 | ORDER BY e.created_at, e.id |
| 39 | LIMIT @page_size; |
| 40 | |
| 41 | -- name: TrialBalance :many |
| 42 | -- Every ledger account's debits and credits before a moment, with customer |
| 43 | -- wallets as one account, and a total per currency, where the two must match. |
| 44 | SELECT currency, coalesce(account, 'total')::text AS account, |
| 45 | sum(debit)::bigint AS debits, sum(credit)::bigint AS credits |
| 46 | FROM ( |
| 47 | SELECT a.currency, CASE a.kind WHEN 'wallet' THEN 'customer wallets' ELSE a.name END AS account, |
| 48 | CASE e.direction WHEN 'debit' THEN e.amount ELSE 0 END AS debit, |
| 49 | CASE e.direction WHEN 'credit' THEN e.amount ELSE 0 END AS credit |
| 50 | FROM entries e |
| 51 | JOIN accounts a ON a.id = e.account_id |
| 52 | WHERE e.created_at < @before |
| 53 | ) AS lines |
| 54 | GROUP BY currency, ROLLUP (account) |
| 55 | ORDER BY currency, account IS NULL, account; |