007_balance_projection.sql 1.0 KB

1234567891011121314151617181920
  1. -- Append-only balance cache points (ADR-0019). A derived, rebuildable read
  2. -- accelerator: each row is one snapshot of a (account, subaccount, asset)
  3. -- balance plus the commit-time watermark (unix millis) it covers, tagged with a
  4. -- Rust-minted monotonic id. Rows are only ever inserted, never updated. A read
  5. -- selects the highest id for the (account, subaccount, asset). The balance is a
  6. -- Cent stored as TEXT, like every other monetary column, and the store never
  7. -- does arithmetic on it.
  8. CREATE TABLE balance_projection (
  9. id BIGINT NOT NULL,
  10. account BIGINT NOT NULL,
  11. subaccount BIGINT NOT NULL DEFAULT 0,
  12. asset INTEGER NOT NULL,
  13. balance TEXT NOT NULL,
  14. watermark BIGINT NOT NULL,
  15. PRIMARY KEY (id)
  16. );
  17. -- The closest-at-or-before read filters by (account, subaccount, asset) and
  18. -- watermark, ordering by watermark then id, so the index leads with those.
  19. CREATE INDEX idx_balance_projection_closest
  20. ON balance_projection (account, subaccount, asset, watermark, id);