Add deposits read table (CQRS projection from bank_to_exchange events)

Project each bank_to_exchange event into a denormalized deposits table
with pre-computed EUR, DKK, and USD amounts using Frankfurter currency
rates. Replaces the aggregate get-deposit-totals query.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-03-08 12:52:32 +01:00
co-authored by Claude Opus 4.6
parent 0446d928e6
commit 174ea24786
5 changed files with 89 additions and 19 deletions
@@ -0,0 +1 @@
DROP TABLE IF EXISTS deposits;
@@ -0,0 +1,12 @@
CREATE TABLE deposits (
id BIGSERIAL PRIMARY KEY,
event_id BIGINT NOT NULL REFERENCES events(id) UNIQUE,
occurred_at TIMESTAMPTZ NOT NULL,
exchange TEXT NOT NULL,
fiat_amount NUMERIC(18,2) NOT NULL,
fiat_currency TEXT NOT NULL,
amount_eur NUMERIC(18,2),
amount_dkk NUMERIC(18,2),
amount_usd NUMERIC(18,2),
note TEXT
);
+14 -11
View File
@@ -82,10 +82,11 @@ SELECT id, name, created_at FROM wallets WHERE id = :id
-- Events --------------------------------------------------------------------
-- :name insert-event! :! :n
-- :doc Insert a new event
-- :name insert-event! :? :1
-- :doc Insert a new event, returning its id
INSERT INTO events (event_type, occurred_at, sats, fee_sats, fiat_amount, fiat_currency, from_wallet_id, to_wallet_id, note)
VALUES (:event-type, :occurred-at, :sats, :fee-sats, :fiat-amount, :fiat-currency, :from-wallet-id, :to-wallet-id, :note)
RETURNING id
-- :name get-all-events :? :*
-- :doc Get all events with wallet names
@@ -125,15 +126,17 @@ LEFT JOIN wallets tw ON tw.id = e.to_wallet_id
WHERE e.from_wallet_id = :wallet-id OR e.to_wallet_id = :wallet-id
ORDER BY e.occurred_at DESC
-- :name get-deposit-totals :? :*
-- :doc Total fiat deposited per exchange per currency from bank_to_exchange events
SELECT tw.name AS exchange, e.fiat_currency AS currency,
SUM(e.fiat_amount) AS total
FROM events e
JOIN wallets tw ON tw.id = e.to_wallet_id
WHERE e.event_type = 'bank_to_exchange'
GROUP BY tw.name, e.fiat_currency
ORDER BY tw.name, e.fiat_currency
-- :name insert-deposit! :! :n
-- :doc Insert a projected deposit row
INSERT INTO deposits (event_id, occurred_at, exchange, fiat_amount, fiat_currency, amount_eur, amount_dkk, amount_usd, note)
VALUES (:event-id, :occurred-at, :exchange, :fiat-amount, :fiat-currency, :amount-eur, :amount-dkk, :amount-usd, :note)
-- :name get-all-deposits :? :*
-- :doc Get all projected deposits ordered by date descending
SELECT id, event_id, occurred_at, exchange, fiat_amount, fiat_currency,
amount_eur, amount_dkk, amount_usd, note
FROM deposits
ORDER BY occurred_at DESC
-- :name get-wallet-balances :? :*
-- :doc Compute sats balance per wallet from events