#![allow(missing_docs)] #![cfg(feature = "sqlite")] use kuatia_storage::events::{LedgerEvent, LedgerEventKind}; use kuatia_storage::store::{ AccountStore, CommitOutcome, CommitRequest, CommitStore, PostingStore, TransferQuery, TransferRecord, TransferStore, }; use kuatia_storage::store_tests::{seed_live, spend_live}; use kuatia_storage_sql::SqlStore; use kuatia_types::internals::{decode_storage_i128, encode_storage_i128}; use kuatia_types::*; use sqlx::{Any, Pool, Row}; /// An amount of `asset` in minor units. These tests assert on ids and values, /// and an amount compares by asset id, so the metadata here is filler. fn money(asset: AssetId, value: V) -> Amount where Amount: From<(V, std::sync::Arc)>, { Amount::from(( value, std::sync::Arc::new(Asset::new(asset, "TEST", "$", 2)), )) } async fn new_pool() -> Pool { kuatia_storage_sql::install_drivers().expect("install sqlite money functions"); sqlx::any::AnyPoolOptions::new() .max_connections(1) .connect("sqlite::memory:") .await .unwrap() } async fn new_store() -> SqlStore { let store = SqlStore::new(new_pool().await); store.migrate().await.unwrap(); store } kuatia_storage::store_tests!(new_store); /// The point of the schema: no identifier or payload column holds opaque /// binary. A content-addressed id is stored as lower-case hex text, and a /// structured payload as readable JSON text. So an audit can read a row in a /// plain SQL client. /// /// Amounts are the one exception. They are stored natively, so the database can /// sum and order them (ADR-0024). `kuatia_i128_to_text` is how a client that /// registered the money functions reads one back. #[tokio::test] async fn columns_store_hex_ids_and_json_text() { let pool = new_pool().await; let store = SqlStore::new(pool.clone()); store.migrate().await.unwrap(); let account = Account { id: AccountId::new(1), version: 1, flags: AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT, book: BookId(0), metadata: std::collections::BTreeMap::new(), }; store.create_account(account).await.unwrap(); let tid = TransferId([0xab; 32]); let posting = Posting::new( PostingId { transfer: tid, index: 0, }, AccountId::new(1), money(AssetId::new(1), 100), ); seed_live(&store, 0xab, &[posting]).await; // The 32-byte transfer id is stored as its 64-char lower-case hex form. let row = sqlx::query("SELECT transfer_id FROM postings") .fetch_one(&pool) .await .unwrap(); let transfer_id: String = row.try_get("transfer_id").unwrap(); assert_eq!(transfer_id, "ab".repeat(32)); // The account payload is readable JSON text, not a blob. let row = sqlx::query("SELECT metadata FROM accounts") .fetch_one(&pool) .await .unwrap(); let metadata: String = row.try_get("metadata").unwrap(); assert!( serde_json::from_str::(&metadata).is_ok(), "metadata should be JSON text, got: {metadata}" ); // The amount is a 16-byte blob, and still legible through the helper. let row = sqlx::query("SELECT typeof(value) AS t, kuatia_i128_to_text(value) AS v FROM postings") .fetch_one(&pool) .await .unwrap(); assert_eq!(row.try_get::("t").unwrap(), "blob"); assert_eq!(row.try_get::("v").unwrap(), "100"); } /// The 002 migration adds the subaccount column. A subaccount account and /// posting round-trip through the schema, and stay distinct from the main /// account. #[tokio::test] async fn subaccount_columns_round_trip() { let store = new_store().await; let sub = AccountId::with_sub(1, 7); store .create_account(Account::debit_must_not_exceed_credit(sub)) .await .unwrap(); // The main account (1, 0) is a separate record. store .create_account(Account::debit_must_not_exceed_credit(AccountId::new(1))) .await .unwrap(); let got = store.get_account(&sub).await.unwrap(); assert_eq!(got.id, sub); let posting = Posting::new( PostingId { transfer: TransferId([0xcd; 32]), index: 0, }, sub, money(AssetId::new(1), 500), ); seed_live(&store, 0xcd, &[posting]).await; // Filtering by the subaccount returns it; the main account holds nothing. let by_sub = store .get_postings_by_account(1, Some(7), None, PostingFilter::All) .await .unwrap(); assert_eq!(by_sub.len(), 1); assert_eq!(by_sub[0].owner, sub); let by_main = store .get_postings_by_account(1, Some(0), None, PostingFilter::All) .await .unwrap(); assert!(by_main.is_empty()); } /// A database created under 001, with no subaccount column, upgrades in place. /// The 002 migration rebuilds the tables, and a row already stored defaults to /// subaccount 0, the main account. #[tokio::test] async fn migration_upgrades_existing_rows_to_main_account() { let pool = new_pool().await; // Pre-002 schema: the tables 002 rebuilds, in their old (no-subaccount) shape. sqlx::query( "CREATE TABLE accounts (id BIGINT NOT NULL, version BIGINT NOT NULL, policy TEXT NOT NULL, flags INTEGER NOT NULL, book BIGINT NOT NULL, user_data TEXT NOT NULL, metadata TEXT NOT NULL, PRIMARY KEY (id, version))", ) .execute(&pool) .await .unwrap(); // 001 is pinned as applied below, so its `transfers` table has to exist: // a migration that alters it would otherwise fail against a fixture that // claims 001 already ran. sqlx::query( "CREATE TABLE transfers (id TEXT PRIMARY KEY, transfer TEXT NOT NULL, receipt TEXT NOT NULL, created_at BIGINT NOT NULL DEFAULT 0, book BIGINT NOT NULL DEFAULT 0)", ) .execute(&pool) .await .unwrap(); sqlx::query( "CREATE TABLE postings (transfer_id TEXT NOT NULL, idx SMALLINT NOT NULL, owner BIGINT NOT NULL, asset INTEGER NOT NULL, value TEXT NOT NULL, status SMALLINT NOT NULL, reservation BIGINT, PRIMARY KEY (transfer_id, idx))", ) .execute(&pool) .await .unwrap(); sqlx::query("CREATE INDEX idx_postings_owner ON postings(owner, asset, status)") .execute(&pool) .await .unwrap(); sqlx::query( "CREATE TABLE transfer_accounts (transfer_id TEXT NOT NULL, account_id BIGINT NOT NULL, PRIMARY KEY (transfer_id, account_id))", ) .execute(&pool) .await .unwrap(); sqlx::query("CREATE INDEX idx_xfer_acct ON transfer_accounts(account_id)") .execute(&pool) .await .unwrap(); // The sagas table has existed since 001; seed it so the 009 ALTER (add the // kind column) has a table to run against on this full-chain upgrade. sqlx::query("CREATE TABLE sagas (id BIGINT PRIMARY KEY, data TEXT NOT NULL)") .execute(&pool) .await .unwrap(); // Legacy 001/002 schema carried a user_data JSON column; the 003 migration // drops it. Seed it with the value the old UserData type serialized to. let user_data = r#"{"d128":0,"d64":0,"d32":0}"#.to_string(); let metadata = serde_json::to_string(&std::collections::BTreeMap::::new()).unwrap(); sqlx::query( "INSERT INTO accounts (id, version, policy, flags, book, user_data, metadata) VALUES (5, 1, '\"NoOverdraft\"', 0, 0, $1, $2)", ) .bind(user_data) .bind(metadata) .execute(&pool) .await .unwrap(); // Record 001 as applied so migrate() only runs 002 against this schema. sqlx::query("CREATE TABLE _migrations (name TEXT PRIMARY KEY)") .execute(&pool) .await .unwrap(); sqlx::query("INSERT INTO _migrations (name) VALUES ('001_init')") .execute(&pool) .await .unwrap(); let store = SqlStore::new(pool); store.migrate().await.unwrap(); // The pre-existing account is now the main account (subaccount 0). let got = store.get_account(&AccountId::new(5)).await.unwrap(); assert_eq!(got.id, AccountId::new(5)); assert!(got.id.is_main()); } /// The 004 migration splits lifecycle state out of `postings` into the two /// id-only index tables. An active posting, status 0, is backfilled into /// `active_postings`. A reserved posting, status 1, goes into /// `reserved_postings` with its token. The `status` column is dropped from /// `postings`. #[tokio::test] async fn migration_004_backfills_index_tables() { let pool = new_pool().await; // Pre-004 postings schema (the shape 001->003 leave it): status + reservation. sqlx::query( "CREATE TABLE postings (transfer_id TEXT NOT NULL, idx SMALLINT NOT NULL, owner BIGINT NOT NULL, subaccount BIGINT NOT NULL DEFAULT 0, asset INTEGER NOT NULL, value TEXT NOT NULL, status SMALLINT NOT NULL, reservation BIGINT, PRIMARY KEY (transfer_id, idx))", ) .execute(&pool) .await .unwrap(); // One active (status 0) and one reserved (status 1, reservation 77) posting. sqlx::query("INSERT INTO postings (transfer_id, idx, owner, subaccount, asset, value, status, reservation) VALUES ('aa', 0, 1, 0, 1, '100', 0, NULL)") .execute(&pool) .await .unwrap(); sqlx::query("INSERT INTO postings (transfer_id, idx, owner, subaccount, asset, value, status, reservation) VALUES ('bb', 0, 1, 0, 1, '200', 1, 77)") .execute(&pool) .await .unwrap(); // A post-003 DB also has the accounts table (empty here). sqlx::query( "CREATE TABLE accounts (id BIGINT NOT NULL, subaccount BIGINT NOT NULL DEFAULT 0, version BIGINT NOT NULL, policy TEXT NOT NULL, flags INTEGER NOT NULL, book BIGINT NOT NULL, metadata TEXT NOT NULL, PRIMARY KEY (id, subaccount, version))", ) .execute(&pool) .await .unwrap(); // Record every migration except 004 as applied so migrate() runs only 004, // isolating its backfill. In particular 008 (which merges the index tables // into `live_postings`) is pinned as applied so it does not run and clobber // the active/reserved tables this test inspects. sqlx::query("CREATE TABLE _migrations (name TEXT PRIMARY KEY)") .execute(&pool) .await .unwrap(); for m in [ "001_init", "002_subaccounts", "003_drop_user_data", "005_account_head", "006_drop_policy", "007_balance_projection", "008_live_postings", "009_saga_kind", "010_drop_sagas", "011_native_amounts", "012_drop_reservation", "013_value_date", ] { sqlx::query("INSERT INTO _migrations (name) VALUES ($1)") .bind(m) .execute(&pool) .await .unwrap(); } let store = SqlStore::new(pool.clone()); store.migrate().await.unwrap(); // The active posting is now in active_postings, carrying a full row copy. let active = sqlx::query("SELECT transfer_id, owner, asset, value FROM active_postings") .fetch_all(&pool) .await .unwrap(); assert_eq!(active.len(), 1); let a_tid: String = active[0].try_get("transfer_id").unwrap(); let a_owner: i64 = active[0].try_get("owner").unwrap(); let a_value: String = active[0].try_get("value").unwrap(); assert_eq!(a_tid, "aa"); assert_eq!(a_owner, 1); assert_eq!(a_value, "100"); // The reserved posting is in reserved_postings with its data copy and token. let reserved = sqlx::query("SELECT transfer_id, value, reservation FROM reserved_postings") .fetch_all(&pool) .await .unwrap(); assert_eq!(reserved.len(), 1); let r_tid: String = reserved[0].try_get("transfer_id").unwrap(); let r_value: String = reserved[0].try_get("value").unwrap(); let r_res: i64 = reserved[0].try_get("reservation").unwrap(); assert_eq!(r_tid, "bb"); assert_eq!(r_value, "200"); assert_eq!(r_res, 77); // Both immutable rows survive; the status column is gone. let all = sqlx::query("SELECT transfer_id FROM postings") .fetch_all(&pool) .await .unwrap(); assert_eq!(all.len(), 2); assert!( sqlx::query("SELECT status FROM postings") .fetch_all(&pool) .await .is_err() ); } /// The 005 migration backfills `account_head` with the current version of each /// account, which is the highest one. So a later read hits one row per account, /// and scans no version history. #[tokio::test] async fn migration_005_backfills_account_head() { let pool = new_pool().await; // Pre-005 accounts schema (post-004 shape) with a versioned history: // account 1 has three versions, account 2 has one. sqlx::query( "CREATE TABLE accounts (id BIGINT NOT NULL, subaccount BIGINT NOT NULL DEFAULT 0, version BIGINT NOT NULL, policy TEXT NOT NULL, flags INTEGER NOT NULL, book BIGINT NOT NULL, metadata TEXT NOT NULL, PRIMARY KEY (id, subaccount, version))", ) .execute(&pool) .await .unwrap(); for (id, version) in [(1, 1), (1, 2), (1, 3), (2, 1)] { sqlx::query("INSERT INTO accounts (id, subaccount, version, policy, flags, book, metadata) VALUES ($1, 0, $2, '\"NoOverdraft\"', 0, 0, '{}')") .bind(id as i64) .bind(version as i64) .execute(&pool) .await .unwrap(); } // Record every migration except 005 as applied so migrate() runs only 005. // 008 and 011 are pinned as applied so they do not run against a DB whose // 004 index tables were never created. sqlx::query("CREATE TABLE _migrations (name TEXT PRIMARY KEY)") .execute(&pool) .await .unwrap(); for m in [ "001_init", "002_subaccounts", "003_drop_user_data", "004_index_tables", "006_drop_policy", "007_balance_projection", "008_live_postings", "009_saga_kind", "010_drop_sagas", "011_native_amounts", "012_drop_reservation", "013_value_date", ] { sqlx::query("INSERT INTO _migrations (name) VALUES ($1)") .bind(m) .execute(&pool) .await .unwrap(); } let store = SqlStore::new(pool.clone()); store.migrate().await.unwrap(); // One head per account, each pointing at the highest version. let mut heads: Vec<(i64, i64)> = sqlx::query("SELECT id, version FROM account_head") .fetch_all(&pool) .await .unwrap() .iter() .map(|r| (r.try_get("id").unwrap(), r.try_get("version").unwrap())) .collect(); heads.sort(); assert_eq!(heads, vec![(1, 3), (2, 1)]); // The store reads the current version through the head. let acct = store.get_account(&AccountId::new(1)).await.unwrap(); assert_eq!(acct.version, 3); } /// The 008 migration merges the two index tables into one `live_postings` /// table. An active row is backfilled with `reservation` NULL, and a reserved /// row keeps its token. The old `active_postings` and `reserved_postings` /// tables are dropped. #[tokio::test] async fn migration_008_merges_live_postings() { let pool = new_pool().await; // Post-004 index tables with one active and one reserved posting. sqlx::query( "CREATE TABLE active_postings (transfer_id TEXT NOT NULL, idx SMALLINT NOT NULL, owner BIGINT NOT NULL, subaccount BIGINT NOT NULL DEFAULT 0, asset INTEGER NOT NULL, value TEXT NOT NULL, PRIMARY KEY (transfer_id, idx))", ) .execute(&pool) .await .unwrap(); sqlx::query( "CREATE TABLE reserved_postings (transfer_id TEXT NOT NULL, idx SMALLINT NOT NULL, owner BIGINT NOT NULL, subaccount BIGINT NOT NULL DEFAULT 0, asset INTEGER NOT NULL, value TEXT NOT NULL, reservation BIGINT NOT NULL, PRIMARY KEY (transfer_id, idx))", ) .execute(&pool) .await .unwrap(); sqlx::query("INSERT INTO active_postings (transfer_id, idx, owner, subaccount, asset, value) VALUES ('aa', 0, 1, 0, 1, '100')") .execute(&pool) .await .unwrap(); sqlx::query("INSERT INTO reserved_postings (transfer_id, idx, owner, subaccount, asset, value, reservation) VALUES ('bb', 0, 1, 0, 1, '200', 77)") .execute(&pool) .await .unwrap(); // Record every migration except 008 as applied so migrate() runs only 008. sqlx::query("CREATE TABLE _migrations (name TEXT PRIMARY KEY)") .execute(&pool) .await .unwrap(); for m in [ "001_init", "002_subaccounts", "003_drop_user_data", "004_index_tables", "005_account_head", "006_drop_policy", "007_balance_projection", "009_saga_kind", "010_drop_sagas", "011_native_amounts", "012_drop_reservation", "013_value_date", ] { sqlx::query("INSERT INTO _migrations (name) VALUES ($1)") .bind(m) .execute(&pool) .await .unwrap(); } let store = SqlStore::new(pool.clone()); store.migrate().await.unwrap(); // The active row lands with reservation NULL, the reserved row keeps its token. let mut rows: Vec<(String, Option)> = sqlx::query("SELECT transfer_id, reservation FROM live_postings") .fetch_all(&pool) .await .unwrap() .iter() .map(|r| { ( r.try_get("transfer_id").unwrap(), r.try_get("reservation").unwrap(), ) }) .collect(); rows.sort(); assert_eq!( rows, vec![("aa".to_string(), None), ("bb".to_string(), Some(77))] ); // The old index tables are gone. assert!( sqlx::query("SELECT 1 FROM active_postings") .fetch_all(&pool) .await .is_err() ); assert!( sqlx::query("SELECT 1 FROM reserved_postings") .fetch_all(&pool) .await .is_err() ); } /// migrate() is idempotent, so a second run on the same database is a no-op. #[tokio::test] async fn migrate_is_idempotent() { kuatia_storage_sql::install_drivers().expect("install sqlite money functions"); let pool = sqlx::any::AnyPoolOptions::new() .max_connections(1) .connect("sqlite::memory:") .await .unwrap(); let store = SqlStore::new(pool); store.migrate().await.unwrap(); store.migrate().await.unwrap(); store.migrate().await.unwrap(); } /// The id-batch primitives chunk a large id set, so it never exceeds the /// bind-parameter limit of the backend. SQLite caps a statement at 32766 /// variables. A batch larger than one chunk must be created, read and spent /// exactly as a small one is. The consume SELECT and DELETE of the commit are /// the chunked writes this guards. #[tokio::test] async fn id_batches_chunk_across_reads_and_commit() { const N: u16 = 9000; let store = new_store().await; let tid = TransferId([0xcd; 32]); let postings: Vec = (0..N) .map(|i| { Posting::new( PostingId { transfer: tid, index: i, }, AccountId::new(1), money(AssetId::new(1), 1), ) }) .collect(); let ids: Vec = postings.iter().map(|p| p.id).collect(); seed_live(&store, 0xcd, &postings).await; let states = store.get_posting_states(&ids).await.unwrap(); assert_eq!(states.len(), N as usize); assert!(states.iter().all(|s| *s == PostingState::Live)); assert_eq!(store.get_postings(&ids).await.unwrap().len(), N as usize); spend_live(&store, 0xce, &ids).await; let after = store.get_posting_states(&ids).await.unwrap(); assert!(after.iter().all(|s| *s == PostingState::Spent)); } fn encoded(value: i128) -> Vec { encode_storage_i128(value).to_vec() } fn decoded(bytes: &[u8]) -> i128 { let bytes: [u8; 16] = bytes.try_into().expect("a 16-byte amount"); decode_storage_i128(&bytes) } /// The money scalars round-trip the full i128 range, which is what the 011 /// migration relies on to convert the old text columns. #[tokio::test] async fn money_scalars_round_trip() { let pool = new_pool().await; for v in [ "0", "1", "-1", "170141183460469231731687303715884105727", "-170141183460469231731687303715884105728", ] { let row = sqlx::query("SELECT kuatia_i128_to_text(kuatia_i128_from_text($1)) AS t") .bind(v) .fetch_one(&pool) .await .unwrap(); assert_eq!(row.try_get::("t").unwrap(), v); } } /// The aggregate folds mixed signs exactly. An empty group sums to zero rather /// than to SQL NULL, so a caller can decode the result unconditionally. #[tokio::test] async fn i128_sum_folds_and_handles_empty_group() { let pool = new_pool().await; sqlx::query("CREATE TABLE amounts (v BLOB NOT NULL)") .execute(&pool) .await .unwrap(); let values: Vec = vec![5, -3, 1_000_000_000_000_000_000_000, -7]; for v in &values { sqlx::query("INSERT INTO amounts (v) VALUES ($1)") .bind(encoded(*v)) .execute(&pool) .await .unwrap(); } let row = sqlx::query("SELECT kuatia_i128_sum(v) AS s FROM amounts") .fetch_one(&pool) .await .unwrap(); assert_eq!( decoded(&row.try_get::, _>("s").unwrap()), values.iter().sum::() ); let row = sqlx::query("SELECT kuatia_i128_sum(v) AS s FROM amounts WHERE 1 = 0") .fetch_one(&pool) .await .unwrap(); assert_eq!(decoded(&row.try_get::, _>("s").unwrap()), 0); } /// The aggregate raises instead of a wrap. That property is what makes a sum in /// SQL as safe as `Cent::checked_sum`. #[tokio::test] async fn i128_sum_overflows_loudly() { let pool = new_pool().await; sqlx::query("CREATE TABLE amounts (v BLOB NOT NULL)") .execute(&pool) .await .unwrap(); for _ in 0..2 { sqlx::query("INSERT INTO amounts (v) VALUES ($1)") .bind(encoded(i128::MAX)) .execute(&pool) .await .unwrap(); } let err = match sqlx::query("SELECT kuatia_i128_sum(v) AS s FROM amounts") .fetch_one(&pool) .await { Ok(_) => panic!("summing past i128::MAX should fail"), Err(e) => e.to_string(), }; assert!(err.contains("i128"), "{err}"); } /// A value that is not a 16-byte amount fails the statement, and the aggregate /// skips none. So a corrupt row can never silently change a balance. #[tokio::test] async fn i128_sum_rejects_non_amount() { let pool = new_pool().await; let err = match sqlx::query("SELECT kuatia_i128_sum(x) AS s FROM (SELECT 'abc' AS x)") .fetch_one(&pool) .await { Ok(_) => panic!("a text argument should fail"), Err(e) => e.to_string(), }; assert!(err.contains("16-byte"), "{err}"); } /// The storage encoding is order-preserving, so the byte-wise BLOB comparison /// of SQLite orders amounts numerically. The text columns could not do that /// (ADR-0011), and it is the reason the encoding flips the sign bit. #[tokio::test] async fn blob_order_matches_numeric_order() { let pool = new_pool().await; sqlx::query("CREATE TABLE amounts (v BLOB NOT NULL)") .execute(&pool) .await .unwrap(); for v in [7i128, -9, 0, i128::MAX, i128::MIN, -1, 1] { sqlx::query("INSERT INTO amounts (v) VALUES ($1)") .bind(encoded(v)) .execute(&pool) .await .unwrap(); } let ordered: Vec = sqlx::query("SELECT kuatia_i128_to_text(v) AS t FROM amounts ORDER BY v") .fetch_all(&pool) .await .unwrap() .iter() .map(|r| r.try_get::("t").unwrap().parse().unwrap()) .collect(); let mut expected = ordered.clone(); expected.sort(); assert_eq!(ordered, expected); assert_eq!(ordered.first(), Some(&i128::MIN)); assert_eq!(ordered.last(), Some(&i128::MAX)); } /// Amounts are stored at full i128 width, so a value past the i64 backing /// round-trips through the store under the `i128` feature. #[cfg(feature = "i128")] #[tokio::test] async fn value_beyond_i64_round_trips() { use kuatia_types::internals::Cent; use std::str::FromStr; let store = new_store().await; let value = Cent::from_str("170141183460469231731687303715884105727").unwrap(); let posting = Posting::new( PostingId { transfer: TransferId([0x5c; 32]), index: 0, }, AccountId::new(1), money(AssetId::new(1), value), ); seed_live(&store, 0x5c, std::slice::from_ref(&posting)).await; let got = store.get_postings(&[posting.id]).await.unwrap(); assert_eq!(got[0].amount.minor_units(), value.minor_units()); assert_eq!( store .live_balance(&AccountId::new(1), &AssetId::new(1)) .await .unwrap() .minor_units(), value.minor_units() ); } /// The 013 migration adds the value-date column, and a row that is already /// there gets NULL. An entry booked before the column existed was valued on the /// day it was booked. #[tokio::test] async fn migration_013_adds_value_date_as_null_for_existing_rows() { let pool = new_pool().await; // Post-012 shape: transfers without a value date. sqlx::query("CREATE TABLE transfers (id TEXT PRIMARY KEY, transfer TEXT NOT NULL, receipt TEXT NOT NULL, created_at BIGINT NOT NULL DEFAULT 0, book BIGINT NOT NULL DEFAULT 0)") .execute(&pool) .await .unwrap(); sqlx::query("INSERT INTO transfers (id, transfer, receipt, created_at, book) VALUES ('aa', '{}', '{}', 5, 0)") .execute(&pool) .await .unwrap(); sqlx::query("CREATE TABLE _migrations (name TEXT PRIMARY KEY)") .execute(&pool) .await .unwrap(); for m in [ "001_init", "002_subaccounts", "003_drop_user_data", "004_index_tables", "005_account_head", "006_drop_policy", "007_balance_projection", "008_live_postings", "009_saga_kind", "010_drop_sagas", "011_native_amounts", "012_drop_reservation", ] { sqlx::query("INSERT INTO _migrations (name) VALUES ($1)") .bind(m) .execute(&pool) .await .unwrap(); } SqlStore::new(pool.clone()).migrate().await.unwrap(); let row = sqlx::query("SELECT value_date FROM transfers WHERE id = 'aa'") .fetch_one(&pool) .await .unwrap(); assert!( row.try_get::, _>("value_date") .unwrap() .is_none(), "an entry booked before the column existed carries no value date" ); } /// The value-date window is a SQL predicate, and not a filter applied after the /// load. So it has to behave the same as the in-memory backend. An entry with /// no value date sits outside an explicit window, and not inside every one. #[tokio::test] async fn value_date_window_filters_in_sql() { let pool = new_pool().await; let store = SqlStore::new(pool.clone()); store.migrate().await.unwrap(); store .create_account(Account::new(AccountId::new(1))) .await .unwrap(); for (tag, day) in [(1u8, Some(18u32)), (2, Some(20)), (3, Some(22)), (4, None)] { let tid = TransferId([tag; 32]); let value_date = day.map(|d| ValueDate::new(2026, 11, d).unwrap()); let mut builder = EnvelopeBuilder::new().creates(vec![NewPosting { owner: AccountId::new(1), amount: money(AssetId::new(1), 10), payer: None, }]); if let Some(date) = value_date { builder = builder.value_date(date); } let envelope = builder.build(); let create = vec![Posting::new( PostingId { transfer: tid, index: 0, }, AccountId::new(1), money(AssetId::new(1), 10), )]; let involved = [AccountId::new(1)]; let outcome = store .commit_envelope(CommitRequest { transfer_id: tid, consume: &[], create: &create, record: TransferRecord { envelope, receipt: Receipt { transfer_id: tid }, created_at: 1000, }, involved: &involved, event: LedgerEvent { seq: 0, timestamp: 1000, kind: LedgerEventKind::TransferCommitted { transfer_id: tid }, }, }) .await .unwrap(); assert!(matches!(outcome, CommitOutcome::Committed(_))); } let page = store .query_transfers(&TransferQuery { account: Some(1), from_value_date: Some(ValueDate::new(2026, 11, 19).unwrap()), to_value_date: Some(ValueDate::new(2026, 11, 22).unwrap()), ..Default::default() }) .await .unwrap(); assert_eq!(page.total, 1, "only the entry valued on the 20th"); assert_eq!( page.items[0].envelope.value_date(), Some(ValueDate::new(2026, 11, 20).unwrap()) ); // The column is written at commit, so the database can answer without // reading the envelope JSON back. let row = sqlx::query("SELECT COUNT(*) AS n FROM transfers WHERE value_date IS NULL") .fetch_one(&pool) .await .unwrap(); assert_eq!(row.try_get::("n").unwrap(), 1); } /// The 012 migration drops the reservation column and leaves every live row /// live. That covers a row that still carried a token. It was never consumed, /// so it must stay spendable and it must still count toward the balance. #[tokio::test] async fn migration_012_drops_reservation_and_keeps_rows_live() { let pool = new_pool().await; // Post-011 shape: native blob amounts, reservation column still present. for ddl in [ "CREATE TABLE postings (transfer_id TEXT NOT NULL, idx SMALLINT NOT NULL, owner BIGINT NOT NULL, subaccount BIGINT NOT NULL DEFAULT 0, asset INTEGER NOT NULL, value BLOB NOT NULL, PRIMARY KEY (transfer_id, idx))", "CREATE TABLE live_postings (transfer_id TEXT NOT NULL, idx SMALLINT NOT NULL, owner BIGINT NOT NULL, subaccount BIGINT NOT NULL DEFAULT 0, asset INTEGER NOT NULL, value BLOB NOT NULL, reservation BIGINT, PRIMARY KEY (transfer_id, idx))", ] { sqlx::query(ddl).execute(&pool).await.unwrap(); } for (tid, value, reservation) in [("aa", 100i128, None), ("bb", 250i128, Some(77i64))] { sqlx::query("INSERT INTO live_postings (transfer_id, idx, owner, subaccount, asset, value, reservation) VALUES ($1, 0, 1, 0, 1, $2, $3)") .bind(tid) .bind(encoded(value)) .bind(reservation) .execute(&pool) .await .unwrap(); } // Record every migration except 012 as applied so migrate() runs only 012. sqlx::query("CREATE TABLE _migrations (name TEXT PRIMARY KEY)") .execute(&pool) .await .unwrap(); for m in [ "001_init", "002_subaccounts", "003_drop_user_data", "004_index_tables", "005_account_head", "006_drop_policy", "007_balance_projection", "008_live_postings", "009_saga_kind", "010_drop_sagas", "011_native_amounts", "013_value_date", ] { sqlx::query("INSERT INTO _migrations (name) VALUES ($1)") .bind(m) .execute(&pool) .await .unwrap(); } let store = SqlStore::new(pool.clone()); store.migrate().await.unwrap(); assert!( sqlx::query("SELECT reservation FROM live_postings") .fetch_all(&pool) .await .is_err(), "the reservation column is gone" ); // Both rows are still live, and the previously reserved one still sums in. let row = sqlx::query("SELECT COUNT(*) AS n, kuatia_i128_sum(value) AS s FROM live_postings") .fetch_one(&pool) .await .unwrap(); assert_eq!(row.try_get::("n").unwrap(), 2); assert_eq!(decoded(&row.try_get::, _>("s").unwrap()), 350); } /// The 011 migration rewrites the text amounts already stored into the native /// blob encoding. It keeps their values, a negative one too, and the rest of /// the row. #[tokio::test] async fn migration_011_converts_text_amounts() { let pool = new_pool().await; // Post-010 shape: money columns are still TEXT. for ddl in [ "CREATE TABLE postings (transfer_id TEXT NOT NULL, idx SMALLINT NOT NULL, owner BIGINT NOT NULL, subaccount BIGINT NOT NULL DEFAULT 0, asset INTEGER NOT NULL, value TEXT NOT NULL, PRIMARY KEY (transfer_id, idx))", "CREATE TABLE live_postings (transfer_id TEXT NOT NULL, idx SMALLINT NOT NULL, owner BIGINT NOT NULL, subaccount BIGINT NOT NULL DEFAULT 0, asset INTEGER NOT NULL, value TEXT NOT NULL, reservation BIGINT, PRIMARY KEY (transfer_id, idx))", "CREATE TABLE balance_projection (id BIGINT NOT NULL, account BIGINT NOT NULL, subaccount BIGINT NOT NULL DEFAULT 0, asset INTEGER NOT NULL, balance TEXT NOT NULL, watermark BIGINT NOT NULL, PRIMARY KEY (id))", "INSERT INTO postings (transfer_id, idx, owner, subaccount, asset, value) VALUES ('aa', 0, 1, 0, 1, '100')", "INSERT INTO postings (transfer_id, idx, owner, subaccount, asset, value) VALUES ('bb', 0, 1, 0, 1, '-250')", "INSERT INTO live_postings (transfer_id, idx, owner, subaccount, asset, value, reservation) VALUES ('aa', 0, 1, 0, 1, '100', 77)", "INSERT INTO balance_projection (id, account, subaccount, asset, balance, watermark) VALUES (1, 1, 0, 1, '-150', 5)", ] { sqlx::query(ddl).execute(&pool).await.unwrap(); } // Record every migration except 011 as applied so migrate() runs only 011. sqlx::query("CREATE TABLE _migrations (name TEXT PRIMARY KEY)") .execute(&pool) .await .unwrap(); for m in [ "001_init", "002_subaccounts", "003_drop_user_data", "004_index_tables", "005_account_head", "006_drop_policy", "007_balance_projection", "008_live_postings", "009_saga_kind", "010_drop_sagas", "012_drop_reservation", "013_value_date", ] { sqlx::query("INSERT INTO _migrations (name) VALUES ($1)") .bind(m) .execute(&pool) .await .unwrap(); } let store = SqlStore::new(pool.clone()); store.migrate().await.unwrap(); let rows = sqlx::query( "SELECT transfer_id, typeof(value) AS t, kuatia_i128_to_text(value) AS v FROM postings ORDER BY transfer_id", ) .fetch_all(&pool) .await .unwrap(); let got: Vec<(String, String, String)> = rows .iter() .map(|r| { ( r.try_get("transfer_id").unwrap(), r.try_get("t").unwrap(), r.try_get("v").unwrap(), ) }) .collect(); assert_eq!( got, vec![ ("aa".to_string(), "blob".to_string(), "100".to_string()), ("bb".to_string(), "blob".to_string(), "-250".to_string()), ] ); // The rest of the row survives, and the summing path reads the new column. let row = sqlx::query("SELECT reservation, kuatia_i128_sum(value) AS s FROM live_postings") .fetch_one(&pool) .await .unwrap(); assert_eq!(row.try_get::("reservation").unwrap(), 77); assert_eq!(decoded(&row.try_get::, _>("s").unwrap()), 100); let row = sqlx::query("SELECT kuatia_i128_to_text(balance) AS b, watermark FROM balance_projection") .fetch_one(&pool) .await .unwrap(); assert_eq!(row.try_get::("b").unwrap(), "-150"); assert_eq!(row.try_get::("watermark").unwrap(), 5); }