Reference for the tables that kuatia-storage-sql creates. This is the composed
end-state after a replay of every migration in
crates/kuatia-storage-sql/src/migrations/, from 001_init through
015_asset_code_unique. It also covers the _migrations bookkeeping table,
which crates/kuatia-storage-sql/src/migrate.rs creates.
This reference must stay current, so update it when a migration lands. For the reason the schema looks this way, read the ADRs it links to and not this file.
Ground rules that keep the catalog terse:
transfer_id + idx.
account_head names the current accounts version. The link between an
account and a transfer is an explicit index table. See
ADR-0003.TEXT. A content-addressed id and an
opaque saga byte string are lower-case hex. A JSON payload is its TEXT
serialization. The store never does arithmetic on any of them.NUMERIC(39,0) on PostgreSQL and a 16-byte BLOB on SQLite. Both
stay at full i128 width, whichever width the i128 cargo feature selects.
Both forms order and compare numerically, and both sum exactly. Postgres uses
plain SUM(). SQLite uses the registered kuatia_i128_sum aggregate, which
raises on overflow rather than a wrap. Rust still computes everything else.
AMOUNT in the diagram below stands for this pair of types. See
ADR-0024.BIGINT. There is no AUTOINCREMENT and no
SERIAL. A snowflake id comes from AutoId. See
ADR-0015.sqlx::Any, except for
the money columns, whose native types differ. That divergence lives in the
Dialect seam and in the per-backend halves of 011_native_amounts.The design rationale lives in five records:
An edge is logical only, because no FOREIGN KEY constraint exists. The
labels name how the ledger relates the rows in Rust.
erDiagram
accounts {
BIGINT id PK
BIGINT subaccount PK
BIGINT version PK
INTEGER flags
BIGINT book
TEXT metadata
}
account_head {
BIGINT id PK
BIGINT subaccount PK
BIGINT version
}
postings {
TEXT transfer_id PK
SMALLINT idx PK
BIGINT owner
BIGINT subaccount
INTEGER asset
AMOUNT value
}
live_postings {
TEXT transfer_id PK
SMALLINT idx PK
BIGINT owner
BIGINT subaccount
INTEGER asset
AMOUNT value
}
transfers {
TEXT id PK
TEXT transfer
TEXT receipt
BIGINT created_at
BIGINT book
BIGINT value_date
}
transfer_accounts {
TEXT transfer_id PK
BIGINT account_id PK
BIGINT subaccount PK
}
books {
BIGINT id PK
TEXT name
TEXT data
}
assets {
INTEGER id PK
TEXT code
TEXT data
}
balance_projection {
BIGINT id PK
BIGINT account
BIGINT subaccount
INTEGER asset
AMOUNT balance
BIGINT watermark
}
events {
BIGINT seq PK
BIGINT timestamp
TEXT kind
TEXT data
TEXT dedup_key UK
}
migrations {
TEXT name PK
}
accounts ||--|| account_head : "head -> current version"
accounts }o--|| books : "book id"
transfers ||--o{ transfer_accounts : "id = transfer_id"
accounts ||--o{ transfer_accounts : "account_id + subaccount"
transfers ||--o{ postings : "id = transfer_id"
postings ||--o| live_postings : "live index copy"
accounts ||--o{ balance_projection : "account + subaccount"
(The _migrations table is shown as migrations; Mermaid entity names cannot
start with an underscore.)
Append-only, versioned accounts with a head pointer. Owned by account.rs
(AccountStore). See ADR-0012 (subaccounts) and
ADR-0020 (account transition
recovery).
accountsEvery account version is an immutable row; a new version is appended, never
updated in place. metadata is JSON.
| Column | Type | Key | Purpose |
|---|---|---|---|
id |
BIGINT |
PK | Base account id. |
subaccount |
BIGINT |
PK | Subaccount code (0 = base). |
version |
BIGINT |
PK | Monotonic version; the chain is gap-free. |
flags |
INTEGER |
AccountFlags bitfield (frozen/closed/inflight, DEBIT_MUST_NOT_EXCEED_CREDIT). |
|
book |
BIGINT |
Owning book id. | |
metadata |
TEXT |
JSON key/value metadata. |
(id, subaccount, version).account_headOne row per account, and it names that account's current version. So a lookup is
one indexed join rather than a scan of the version chain. The store maintains it
by a delete and an insert, never by an UPDATE.
| Column | Type | Key | Purpose |
|---|---|---|---|
id |
BIGINT |
PK | Base account id. |
subaccount |
BIGINT |
PK | Subaccount code. |
version |
BIGINT |
The current version in accounts. |
(id, subaccount).A posting is a signed amount of one asset owned by one (sub)account, identified
by (transfer_id, idx). The immutable postings record is the source of truth
for history. One live_postings hot table holds a full row copy of the unspent
set, so a read of what is spendable never merges back to history.
The ledger derives a posting's state from live_postings membership. A row
present there is Live. A row in postings alone is Spent. A row in neither
is Missing. Owned by posting.rs (PostingStore). See ADR-0016 (immutable
postings + index tables),
ADR-0017 (full-row hot
copies), ADR-0022
(merged hot index), ADR-0025 (one
live set).
Why one hot table with full-row copies? The index held only ids in two
tables at the start (ADR-0016).
ADR-0017 moved to
full-row copies. ADR-0022 merged
the active and reserved tables into one live_postings.
ADR-0025 then dropped the
reservation column that had told them apart.
The hot read asks what an account can spend in one asset, and
get_postings_by_account, query_postings and the balance sum all ask it. The
data columns sit in live_postings, so that table can hold
idx_live_owner(owner, subaccount, asset). A live read is then one index scan
over a small table. It needs no join back to history and no UNION, because the
index is the table.
The duplication is safe, because the copied columns are immutable. The ledger
inserts and deletes a live_postings row and never updates one, and a
postings row never changes. So a copy cannot drift from its value row.
The duplication is also bounded and disposable. Only the live set has a copy,
because a spent posting lives in postings alone. live_postings is
rebuildable from postings plus the transfer log, so a corrupt or stale index
is a rebuild and not a loss.
postingsThe immutable record. A row here that is absent from live_postings is Spent.
| Column | Type | Key | Purpose |
|---|---|---|---|
transfer_id |
TEXT |
PK | Creating transfer's id (hex). |
idx |
SMALLINT |
PK | Position within that transfer. |
owner |
BIGINT |
Owning base account id. | |
subaccount |
BIGINT |
Owning subaccount code. | |
asset |
INTEGER |
Asset id. | |
value |
NUMERIC(39,0) / BLOB |
Signed Cent, stored natively: NUMERIC(39,0) on PostgreSQL, the 16-byte order-preserving encoding on SQLite. Read a SQLite one with kuatia_i128_to_text(value). |
(transfer_id, idx).idx_postings_owner (owner, subaccount, asset).live_postingsThe live-set hot copy. A posting sits here while it is spendable. An atomic
commit deletes the consumed row directly, which makes the posting Spent. So
membership is the whole of its state. Rebuildable from postings and the
transfer log.
| Column | Type | Key | Purpose |
|---|---|---|---|
transfer_id |
TEXT |
PK | Posting id (hex). |
idx |
SMALLINT |
PK | Position within the transfer. |
owner |
BIGINT |
Owning base account id. | |
subaccount |
BIGINT |
Owning subaccount code. | |
asset |
INTEGER |
Asset id. | |
value |
NUMERIC(39,0) / BLOB |
Signed Cent, stored natively: NUMERIC(39,0) on PostgreSQL, the 16-byte order-preserving encoding on SQLite. Read a SQLite one with kuatia_i128_to_text(value). |
(transfer_id, idx).idx_live_owner (owner, subaccount, asset).Committed envelope records and the account index that finds them. Owned by
transfer.rs (TransferStore).
transfers| Column | Type | Key | Purpose |
|---|---|---|---|
id |
TEXT |
PK | Content-addressed envelope id (hex). |
transfer |
TEXT |
The Envelope as JSON. |
|
receipt |
TEXT |
The Receipt as JSON. |
|
created_at |
BIGINT |
Unix millis when the ledger committed this entry (default 0). Never caller-supplied: the balance cache folds its tail against it (ADR-0019). |
|
book |
BIGINT |
Owning book id (default 0). |
|
value_date |
BIGINT |
Days since 1970-01-01 for the day this entry takes effect; NULL means the day it was committed. A filterable projection of Envelope.value_date, written at commit and never read back (ADR-0027). |
id.idx_transfers_created_at (created_at),
idx_transfers_book (book), idx_transfers_value_date (value_date).transfer_accountsThe account -> transfer index; the caller supplies the involved set, the store does no computation.
| Column | Type | Key | Purpose |
|---|---|---|---|
transfer_id |
TEXT |
PK | The transfer id (hex). |
account_id |
BIGINT |
PK | An involved base account id. |
subaccount |
BIGINT |
PK | The involved subaccount code. |
(transfer_id, account_id, subaccount).idx_xfer_acct (account_id, subaccount).Migration 010_drop_sagas dropped the sagas write-ahead table. A commit and
an account transition are each one atomic store transaction now (ADR-0023, which
supersedes ADR-0003). So no half-applied state exists for a write-ahead record
to recover.
eventsThe append-only ledger event log, idempotent on the dedup key. Owned by
event.rs (EventStore). See ADR-0010 (event stream vs transfer
log).
| Column | Type | Key | Purpose |
|---|---|---|---|
seq |
BIGINT |
PK | Monotonic sequence number. |
timestamp |
BIGINT |
Unix millis of the event. | |
kind |
TEXT |
Event kind tag (JSON). | |
data |
TEXT |
The full LedgerEvent as JSON. |
|
dedup_key |
TEXT |
UNIQUE | Stable key; a replayed event returns the existing seq. |
seq. Unique: dedup_key.booksBook definitions (asset/account/flag policy) as JSON. Owned by book.rs
(BookStore). See ADR-0013 (journaling model).
| Column | Type | Key | Purpose |
|---|---|---|---|
id |
BIGINT |
PK | Book id. |
name |
TEXT |
Human-readable name. | |
data |
TEXT |
The Book (with its BookPolicy) as JSON. |
id.assetsThe asset registry: what each AssetId means and the decimal places its amounts
are written at. Owned by asset.rs (AssetStore). A row is inserted once and
never updated, which is what lets the ledger cache one for the life of the
process. See ADR-0028 (an amount carries its
asset).
| Column | Type | Key | Purpose |
|---|---|---|---|
id |
INTEGER |
PK | Asset id, a u32 the ledger mints (ADR-0030). |
code |
TEXT |
Short code (USD), duplicated out of data to stay readable in a query. |
|
data |
TEXT |
The Asset as JSON. |
id.idx_assets_code (code), unique. A code is how a caller names an
asset (ADR-0030), so two rows must not share one. Without the index, a
get-or-create keyed on the code could register a second EUR under another id
and split every balance in it.A posting read left-joins this table to rebuild the amount it returns, since a posting carries an amount and an amount carries its asset. The join is deliberately a left join and there is no foreign key. An inner join would quietly drop a posting whose asset is absent. A left join fails the decode instead and says so. The invariant lives at the commit, which resolves every asset a transfer moves value in (ADR-0029).
balance_projectionAppend-only balance cache points: each row snapshots one
(account, subaccount, asset) balance at a commit-time watermark. Rows are only
inserted; a read picks the highest-id row at or before a watermark. A derived,
rebuildable accelerator, never authoritative. Owned by projection.rs
(BalanceProjectionStore). See
ADR-0019.
| Column | Type | Key | Purpose |
|---|---|---|---|
id |
BIGINT |
PK | Rust-minted monotonic id (tie-breaker for equal watermarks). |
account |
BIGINT |
Base account id. | |
subaccount |
BIGINT |
Subaccount code. | |
asset |
INTEGER |
Asset id. | |
balance |
NUMERIC(39,0) / BLOB |
The cached Cent, stored natively (see postings.value). |
|
watermark |
BIGINT |
Commit-time watermark (unix millis) this snapshot covers. |
id.idx_balance_projection_closest (account, subaccount, asset, watermark, id)._migrationsThe applied-migration ledger. Created in migrate.rs (not a .sql file); a
migration whose name is present is skipped, which makes migrate()
idempotent.
| Column | Type | Key | Purpose |
|---|---|---|---|
name |
TEXT |
PK | The migration name (e.g. 011_native_amounts). |
name.SQLite has no 128-bit integer, so an amount is a 16-byte BLOB and three
registered functions do the work the type system would otherwise do. They are
installed by kuatia_storage_sql::install_drivers(). A caller uses that in
place of sqlx::any::install_default_drivers(), and must call it before it
connects a pool. Registration goes through sqlite3_auto_extension, so a
connection that opened earlier does not have the functions. migrate() checks
for them on SQLite and returns StoreError::Misconfigured, rather than a bare
"no such function".
| Function | Signature | Purpose |
|---|---|---|
kuatia_i128_sum |
BLOB → BLOB (aggregate) |
Exact sum of an amount column. Folds with i128::checked_add and raises on overflow or on an argument that is not a 16-byte amount; an empty group sums to zero, not NULL. The PostgreSQL equivalent is plain SUM(). |
kuatia_i128_from_text |
TEXT → BLOB |
Decimal string to the stored encoding. Used by 011_native_amounts to convert the old text columns. |
kuatia_i128_to_text |
BLOB → TEXT |
The stored encoding back to a decimal string, for tooling built on this crate. |
The encoding is two's-complement big-endian with the sign bit flipped. So
SQLite's byte-wise BLOB comparison orders amounts numerically. i128::MIN is
all zeros, 0 is 0x80 and then zeros, and i128::MAX is all 0xFF. It is
deliberately not the content-addressed hash encoding,
Cent::to_canonical_bytes, so nothing can confuse the two.
These functions live in the process that registers them, so a plain sqlite3
CLI does not have them, and it sees a blob. To read one by hand there, take
hex(value), subtract 0x80 from the first byte, and read the result as a
128-bit big-endian two's-complement integer.
This is the one place where the schema is no longer legible without a tool. That is the price of an amount column that the database can sum and order (ADR-0024).