sqlite.rs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005
  1. #![allow(missing_docs)]
  2. #![cfg(feature = "sqlite")]
  3. use kuatia_storage::events::{LedgerEvent, LedgerEventKind};
  4. use kuatia_storage::store::{
  5. AccountStore, CommitOutcome, CommitRequest, CommitStore, PostingStore, TransferQuery,
  6. TransferRecord, TransferStore,
  7. };
  8. use kuatia_storage::store_tests::{seed_live, spend_live};
  9. use kuatia_storage_sql::SqlStore;
  10. use kuatia_types::*;
  11. use sqlx::{Any, Pool, Row};
  12. async fn new_pool() -> Pool<Any> {
  13. kuatia_storage_sql::install_drivers().expect("install sqlite money functions");
  14. sqlx::any::AnyPoolOptions::new()
  15. .max_connections(1)
  16. .connect("sqlite::memory:")
  17. .await
  18. .unwrap()
  19. }
  20. async fn new_store() -> SqlStore {
  21. let store = SqlStore::new(new_pool().await);
  22. store.migrate().await.unwrap();
  23. store
  24. }
  25. kuatia_storage::store_tests!(new_store);
  26. /// The point of the schema: no identifier or payload column holds opaque
  27. /// binary. A content-addressed id is stored as lower-case hex text, and a
  28. /// structured payload as readable JSON text, so a row can be audited in a plain
  29. /// SQL client. Amounts are the one exception, stored natively so the database
  30. /// can sum and order them (ADR-0024); `kuatia_i128_to_text` is how a client that
  31. /// registered the money functions reads one back.
  32. #[tokio::test]
  33. async fn columns_store_hex_ids_and_json_text() {
  34. let pool = new_pool().await;
  35. let store = SqlStore::new(pool.clone());
  36. store.migrate().await.unwrap();
  37. let account = Account {
  38. id: AccountId::new(1),
  39. version: 1,
  40. flags: AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT,
  41. book: BookId(0),
  42. metadata: std::collections::BTreeMap::new(),
  43. };
  44. store.create_account(account).await.unwrap();
  45. let tid = TransferId([0xab; 32]);
  46. let posting = Posting::new(
  47. PostingId {
  48. transfer: tid,
  49. index: 0,
  50. },
  51. AccountId::new(1),
  52. AssetId::new(1),
  53. Cent::from(100),
  54. );
  55. seed_live(&store, 0xab, &[posting]).await;
  56. // The 32-byte transfer id is stored as its 64-char lower-case hex form.
  57. let row = sqlx::query("SELECT transfer_id FROM postings")
  58. .fetch_one(&pool)
  59. .await
  60. .unwrap();
  61. let transfer_id: String = row.try_get("transfer_id").unwrap();
  62. assert_eq!(transfer_id, "ab".repeat(32));
  63. // The account payload is readable JSON text, not a blob.
  64. let row = sqlx::query("SELECT metadata FROM accounts")
  65. .fetch_one(&pool)
  66. .await
  67. .unwrap();
  68. let metadata: String = row.try_get("metadata").unwrap();
  69. assert!(
  70. serde_json::from_str::<serde_json::Value>(&metadata).is_ok(),
  71. "metadata should be JSON text, got: {metadata}"
  72. );
  73. // The amount is a 16-byte blob, and still legible through the helper.
  74. let row =
  75. sqlx::query("SELECT typeof(value) AS t, kuatia_i128_to_text(value) AS v FROM postings")
  76. .fetch_one(&pool)
  77. .await
  78. .unwrap();
  79. assert_eq!(row.try_get::<String, _>("t").unwrap(), "blob");
  80. assert_eq!(row.try_get::<String, _>("v").unwrap(), "100");
  81. }
  82. /// The 002 migration adds the subaccount column and a subaccount account/posting
  83. /// round-trips through the schema, kept distinct from the main account.
  84. #[tokio::test]
  85. async fn subaccount_columns_round_trip() {
  86. let store = new_store().await;
  87. let sub = AccountId::with_sub(1, 7);
  88. store
  89. .create_account(Account::debit_must_not_exceed_credit(sub))
  90. .await
  91. .unwrap();
  92. // The main account (1, 0) is a separate record.
  93. store
  94. .create_account(Account::debit_must_not_exceed_credit(AccountId::new(1)))
  95. .await
  96. .unwrap();
  97. let got = store.get_account(&sub).await.unwrap();
  98. assert_eq!(got.id, sub);
  99. let posting = Posting::new(
  100. PostingId {
  101. transfer: TransferId([0xcd; 32]),
  102. index: 0,
  103. },
  104. sub,
  105. AssetId::new(1),
  106. Cent::from(500),
  107. );
  108. seed_live(&store, 0xcd, &[posting]).await;
  109. // Filtering by the subaccount returns it; the main account holds nothing.
  110. let by_sub = store
  111. .get_postings_by_account(1, Some(7), None, PostingFilter::All)
  112. .await
  113. .unwrap();
  114. assert_eq!(by_sub.len(), 1);
  115. assert_eq!(by_sub[0].owner, sub);
  116. let by_main = store
  117. .get_postings_by_account(1, Some(0), None, PostingFilter::All)
  118. .await
  119. .unwrap();
  120. assert!(by_main.is_empty());
  121. }
  122. /// A database created under 001 (no subaccount column) upgrades in place: the
  123. /// 002 migration rebuilds the tables and existing rows default to subaccount 0,
  124. /// the main account.
  125. #[tokio::test]
  126. async fn migration_upgrades_existing_rows_to_main_account() {
  127. let pool = new_pool().await;
  128. // Pre-002 schema: the tables 002 rebuilds, in their old (no-subaccount) shape.
  129. sqlx::query(
  130. "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))",
  131. )
  132. .execute(&pool)
  133. .await
  134. .unwrap();
  135. // 001 is pinned as applied below, so its `transfers` table has to exist:
  136. // a migration that alters it would otherwise fail against a fixture that
  137. // claims 001 already ran.
  138. sqlx::query(
  139. "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)",
  140. )
  141. .execute(&pool)
  142. .await
  143. .unwrap();
  144. sqlx::query(
  145. "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))",
  146. )
  147. .execute(&pool)
  148. .await
  149. .unwrap();
  150. sqlx::query("CREATE INDEX idx_postings_owner ON postings(owner, asset, status)")
  151. .execute(&pool)
  152. .await
  153. .unwrap();
  154. sqlx::query(
  155. "CREATE TABLE transfer_accounts (transfer_id TEXT NOT NULL, account_id BIGINT NOT NULL, PRIMARY KEY (transfer_id, account_id))",
  156. )
  157. .execute(&pool)
  158. .await
  159. .unwrap();
  160. sqlx::query("CREATE INDEX idx_xfer_acct ON transfer_accounts(account_id)")
  161. .execute(&pool)
  162. .await
  163. .unwrap();
  164. // The sagas table has existed since 001; seed it so the 009 ALTER (add the
  165. // kind column) has a table to run against on this full-chain upgrade.
  166. sqlx::query("CREATE TABLE sagas (id BIGINT PRIMARY KEY, data TEXT NOT NULL)")
  167. .execute(&pool)
  168. .await
  169. .unwrap();
  170. // Legacy 001/002 schema carried a user_data JSON column; the 003 migration
  171. // drops it. Seed it with the value the old UserData type serialized to.
  172. let user_data = r#"{"d128":0,"d64":0,"d32":0}"#.to_string();
  173. let metadata =
  174. serde_json::to_string(&std::collections::BTreeMap::<String, String>::new()).unwrap();
  175. sqlx::query(
  176. "INSERT INTO accounts (id, version, policy, flags, book, user_data, metadata) VALUES (5, 1, '\"NoOverdraft\"', 0, 0, $1, $2)",
  177. )
  178. .bind(user_data)
  179. .bind(metadata)
  180. .execute(&pool)
  181. .await
  182. .unwrap();
  183. // Record 001 as applied so migrate() only runs 002 against this schema.
  184. sqlx::query("CREATE TABLE _migrations (name TEXT PRIMARY KEY)")
  185. .execute(&pool)
  186. .await
  187. .unwrap();
  188. sqlx::query("INSERT INTO _migrations (name) VALUES ('001_init')")
  189. .execute(&pool)
  190. .await
  191. .unwrap();
  192. let store = SqlStore::new(pool);
  193. store.migrate().await.unwrap();
  194. // The pre-existing account is now the main account (subaccount 0).
  195. let got = store.get_account(&AccountId::new(5)).await.unwrap();
  196. assert_eq!(got.id, AccountId::new(5));
  197. assert!(got.id.is_main());
  198. }
  199. /// The 004 migration splits lifecycle state out of `postings` into the two
  200. /// id-only index tables: an active (status 0) posting is backfilled into
  201. /// `active_postings`, a reserved (status 1) posting into `reserved_postings`
  202. /// with its token, and the `status` column is dropped from `postings`.
  203. #[tokio::test]
  204. async fn migration_004_backfills_index_tables() {
  205. let pool = new_pool().await;
  206. // Pre-004 postings schema (the shape 001->003 leave it): status + reservation.
  207. sqlx::query(
  208. "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))",
  209. )
  210. .execute(&pool)
  211. .await
  212. .unwrap();
  213. // One active (status 0) and one reserved (status 1, reservation 77) posting.
  214. sqlx::query("INSERT INTO postings (transfer_id, idx, owner, subaccount, asset, value, status, reservation) VALUES ('aa', 0, 1, 0, 1, '100', 0, NULL)")
  215. .execute(&pool)
  216. .await
  217. .unwrap();
  218. sqlx::query("INSERT INTO postings (transfer_id, idx, owner, subaccount, asset, value, status, reservation) VALUES ('bb', 0, 1, 0, 1, '200', 1, 77)")
  219. .execute(&pool)
  220. .await
  221. .unwrap();
  222. // A post-003 DB also has the accounts table (empty here).
  223. sqlx::query(
  224. "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))",
  225. )
  226. .execute(&pool)
  227. .await
  228. .unwrap();
  229. // Record every migration except 004 as applied so migrate() runs only 004,
  230. // isolating its backfill. In particular 008 (which merges the index tables
  231. // into `live_postings`) is pinned as applied so it does not run and clobber
  232. // the active/reserved tables this test inspects.
  233. sqlx::query("CREATE TABLE _migrations (name TEXT PRIMARY KEY)")
  234. .execute(&pool)
  235. .await
  236. .unwrap();
  237. for m in [
  238. "001_init",
  239. "002_subaccounts",
  240. "003_drop_user_data",
  241. "005_account_head",
  242. "006_drop_policy",
  243. "007_balance_projection",
  244. "008_live_postings",
  245. "009_saga_kind",
  246. "010_drop_sagas",
  247. "011_native_amounts",
  248. "012_drop_reservation",
  249. "013_value_date",
  250. ] {
  251. sqlx::query("INSERT INTO _migrations (name) VALUES ($1)")
  252. .bind(m)
  253. .execute(&pool)
  254. .await
  255. .unwrap();
  256. }
  257. let store = SqlStore::new(pool.clone());
  258. store.migrate().await.unwrap();
  259. // The active posting is now in active_postings, carrying a full row copy.
  260. let active = sqlx::query("SELECT transfer_id, owner, asset, value FROM active_postings")
  261. .fetch_all(&pool)
  262. .await
  263. .unwrap();
  264. assert_eq!(active.len(), 1);
  265. let a_tid: String = active[0].try_get("transfer_id").unwrap();
  266. let a_owner: i64 = active[0].try_get("owner").unwrap();
  267. let a_value: String = active[0].try_get("value").unwrap();
  268. assert_eq!(a_tid, "aa");
  269. assert_eq!(a_owner, 1);
  270. assert_eq!(a_value, "100");
  271. // The reserved posting is in reserved_postings with its data copy and token.
  272. let reserved = sqlx::query("SELECT transfer_id, value, reservation FROM reserved_postings")
  273. .fetch_all(&pool)
  274. .await
  275. .unwrap();
  276. assert_eq!(reserved.len(), 1);
  277. let r_tid: String = reserved[0].try_get("transfer_id").unwrap();
  278. let r_value: String = reserved[0].try_get("value").unwrap();
  279. let r_res: i64 = reserved[0].try_get("reservation").unwrap();
  280. assert_eq!(r_tid, "bb");
  281. assert_eq!(r_value, "200");
  282. assert_eq!(r_res, 77);
  283. // Both immutable rows survive; the status column is gone.
  284. let all = sqlx::query("SELECT transfer_id FROM postings")
  285. .fetch_all(&pool)
  286. .await
  287. .unwrap();
  288. assert_eq!(all.len(), 2);
  289. assert!(
  290. sqlx::query("SELECT status FROM postings")
  291. .fetch_all(&pool)
  292. .await
  293. .is_err()
  294. );
  295. }
  296. /// The 005 migration backfills `account_head` with the current (highest)
  297. /// version of each account, so a subsequent read hits one row per account
  298. /// without scanning the version history.
  299. #[tokio::test]
  300. async fn migration_005_backfills_account_head() {
  301. let pool = new_pool().await;
  302. // Pre-005 accounts schema (post-004 shape) with a versioned history:
  303. // account 1 has three versions, account 2 has one.
  304. sqlx::query(
  305. "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))",
  306. )
  307. .execute(&pool)
  308. .await
  309. .unwrap();
  310. for (id, version) in [(1, 1), (1, 2), (1, 3), (2, 1)] {
  311. sqlx::query("INSERT INTO accounts (id, subaccount, version, policy, flags, book, metadata) VALUES ($1, 0, $2, '\"NoOverdraft\"', 0, 0, '{}')")
  312. .bind(id as i64)
  313. .bind(version as i64)
  314. .execute(&pool)
  315. .await
  316. .unwrap();
  317. }
  318. // Record every migration except 005 as applied so migrate() runs only 005.
  319. // 008 and 011 are pinned as applied so they do not run against a DB whose
  320. // 004 index tables were never created.
  321. sqlx::query("CREATE TABLE _migrations (name TEXT PRIMARY KEY)")
  322. .execute(&pool)
  323. .await
  324. .unwrap();
  325. for m in [
  326. "001_init",
  327. "002_subaccounts",
  328. "003_drop_user_data",
  329. "004_index_tables",
  330. "006_drop_policy",
  331. "007_balance_projection",
  332. "008_live_postings",
  333. "009_saga_kind",
  334. "010_drop_sagas",
  335. "011_native_amounts",
  336. "012_drop_reservation",
  337. "013_value_date",
  338. ] {
  339. sqlx::query("INSERT INTO _migrations (name) VALUES ($1)")
  340. .bind(m)
  341. .execute(&pool)
  342. .await
  343. .unwrap();
  344. }
  345. let store = SqlStore::new(pool.clone());
  346. store.migrate().await.unwrap();
  347. // One head per account, each pointing at the highest version.
  348. let mut heads: Vec<(i64, i64)> = sqlx::query("SELECT id, version FROM account_head")
  349. .fetch_all(&pool)
  350. .await
  351. .unwrap()
  352. .iter()
  353. .map(|r| (r.try_get("id").unwrap(), r.try_get("version").unwrap()))
  354. .collect();
  355. heads.sort();
  356. assert_eq!(heads, vec![(1, 3), (2, 1)]);
  357. // The store reads the current version through the head.
  358. let acct = store.get_account(&AccountId::new(1)).await.unwrap();
  359. assert_eq!(acct.version, 3);
  360. }
  361. /// The 008 migration merges the two index tables into one `live_postings`
  362. /// table: an active row is backfilled with `reservation` NULL, a reserved row
  363. /// keeps its token, and the old `active_postings`/`reserved_postings` tables are
  364. /// dropped.
  365. #[tokio::test]
  366. async fn migration_008_merges_live_postings() {
  367. let pool = new_pool().await;
  368. // Post-004 index tables with one active and one reserved posting.
  369. sqlx::query(
  370. "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))",
  371. )
  372. .execute(&pool)
  373. .await
  374. .unwrap();
  375. sqlx::query(
  376. "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))",
  377. )
  378. .execute(&pool)
  379. .await
  380. .unwrap();
  381. sqlx::query("INSERT INTO active_postings (transfer_id, idx, owner, subaccount, asset, value) VALUES ('aa', 0, 1, 0, 1, '100')")
  382. .execute(&pool)
  383. .await
  384. .unwrap();
  385. sqlx::query("INSERT INTO reserved_postings (transfer_id, idx, owner, subaccount, asset, value, reservation) VALUES ('bb', 0, 1, 0, 1, '200', 77)")
  386. .execute(&pool)
  387. .await
  388. .unwrap();
  389. // Record every migration except 008 as applied so migrate() runs only 008.
  390. sqlx::query("CREATE TABLE _migrations (name TEXT PRIMARY KEY)")
  391. .execute(&pool)
  392. .await
  393. .unwrap();
  394. for m in [
  395. "001_init",
  396. "002_subaccounts",
  397. "003_drop_user_data",
  398. "004_index_tables",
  399. "005_account_head",
  400. "006_drop_policy",
  401. "007_balance_projection",
  402. "009_saga_kind",
  403. "010_drop_sagas",
  404. "011_native_amounts",
  405. "012_drop_reservation",
  406. "013_value_date",
  407. ] {
  408. sqlx::query("INSERT INTO _migrations (name) VALUES ($1)")
  409. .bind(m)
  410. .execute(&pool)
  411. .await
  412. .unwrap();
  413. }
  414. let store = SqlStore::new(pool.clone());
  415. store.migrate().await.unwrap();
  416. // The active row lands with reservation NULL, the reserved row keeps its token.
  417. let mut rows: Vec<(String, Option<i64>)> =
  418. sqlx::query("SELECT transfer_id, reservation FROM live_postings")
  419. .fetch_all(&pool)
  420. .await
  421. .unwrap()
  422. .iter()
  423. .map(|r| {
  424. (
  425. r.try_get("transfer_id").unwrap(),
  426. r.try_get("reservation").unwrap(),
  427. )
  428. })
  429. .collect();
  430. rows.sort();
  431. assert_eq!(
  432. rows,
  433. vec![("aa".to_string(), None), ("bb".to_string(), Some(77))]
  434. );
  435. // The old index tables are gone.
  436. assert!(
  437. sqlx::query("SELECT 1 FROM active_postings")
  438. .fetch_all(&pool)
  439. .await
  440. .is_err()
  441. );
  442. assert!(
  443. sqlx::query("SELECT 1 FROM reserved_postings")
  444. .fetch_all(&pool)
  445. .await
  446. .is_err()
  447. );
  448. }
  449. /// migrate() is idempotent: running it repeatedly on the same DB is a no-op.
  450. #[tokio::test]
  451. async fn migrate_is_idempotent() {
  452. kuatia_storage_sql::install_drivers().expect("install sqlite money functions");
  453. let pool = sqlx::any::AnyPoolOptions::new()
  454. .max_connections(1)
  455. .connect("sqlite::memory:")
  456. .await
  457. .unwrap();
  458. let store = SqlStore::new(pool);
  459. store.migrate().await.unwrap();
  460. store.migrate().await.unwrap();
  461. store.migrate().await.unwrap();
  462. }
  463. /// The id-batch primitives chunk a large id set so it never exceeds the
  464. /// backend's bind-parameter limit (SQLite caps a statement at 32766 variables).
  465. /// A batch larger than one chunk must be created, read, and spent exactly as a
  466. /// small one is. The commit's consume SELECT and DELETE are the chunked writes
  467. /// this guards.
  468. #[tokio::test]
  469. async fn id_batches_chunk_across_reads_and_commit() {
  470. const N: u16 = 9000;
  471. let store = new_store().await;
  472. let tid = TransferId([0xcd; 32]);
  473. let postings: Vec<Posting> = (0..N)
  474. .map(|i| {
  475. Posting::new(
  476. PostingId {
  477. transfer: tid,
  478. index: i,
  479. },
  480. AccountId::new(1),
  481. AssetId::new(1),
  482. Cent::from(1),
  483. )
  484. })
  485. .collect();
  486. let ids: Vec<PostingId> = postings.iter().map(|p| p.id).collect();
  487. seed_live(&store, 0xcd, &postings).await;
  488. let states = store.get_posting_states(&ids).await.unwrap();
  489. assert_eq!(states.len(), N as usize);
  490. assert!(states.iter().all(|s| *s == PostingState::Live));
  491. assert_eq!(store.get_postings(&ids).await.unwrap().len(), N as usize);
  492. spend_live(&store, 0xce, &ids).await;
  493. let after = store.get_posting_states(&ids).await.unwrap();
  494. assert!(after.iter().all(|s| *s == PostingState::Spent));
  495. }
  496. fn encoded(value: i128) -> Vec<u8> {
  497. encode_storage_i128(value).to_vec()
  498. }
  499. fn decoded(bytes: &[u8]) -> i128 {
  500. let bytes: [u8; 16] = bytes.try_into().expect("a 16-byte amount");
  501. decode_storage_i128(&bytes)
  502. }
  503. /// The money scalars round-trip the full i128 range, which is what the 011
  504. /// migration relies on to convert the old text columns.
  505. #[tokio::test]
  506. async fn money_scalars_round_trip() {
  507. let pool = new_pool().await;
  508. for v in [
  509. "0",
  510. "1",
  511. "-1",
  512. "170141183460469231731687303715884105727",
  513. "-170141183460469231731687303715884105728",
  514. ] {
  515. let row = sqlx::query("SELECT kuatia_i128_to_text(kuatia_i128_from_text($1)) AS t")
  516. .bind(v)
  517. .fetch_one(&pool)
  518. .await
  519. .unwrap();
  520. assert_eq!(row.try_get::<String, _>("t").unwrap(), v);
  521. }
  522. }
  523. /// The aggregate folds mixed signs exactly, and an empty group sums to zero
  524. /// rather than to SQL NULL, so a caller can decode the result unconditionally.
  525. #[tokio::test]
  526. async fn i128_sum_folds_and_handles_empty_group() {
  527. let pool = new_pool().await;
  528. sqlx::query("CREATE TABLE amounts (v BLOB NOT NULL)")
  529. .execute(&pool)
  530. .await
  531. .unwrap();
  532. let values: Vec<i128> = vec![5, -3, 1_000_000_000_000_000_000_000, -7];
  533. for v in &values {
  534. sqlx::query("INSERT INTO amounts (v) VALUES ($1)")
  535. .bind(encoded(*v))
  536. .execute(&pool)
  537. .await
  538. .unwrap();
  539. }
  540. let row = sqlx::query("SELECT kuatia_i128_sum(v) AS s FROM amounts")
  541. .fetch_one(&pool)
  542. .await
  543. .unwrap();
  544. assert_eq!(
  545. decoded(&row.try_get::<Vec<u8>, _>("s").unwrap()),
  546. values.iter().sum::<i128>()
  547. );
  548. let row = sqlx::query("SELECT kuatia_i128_sum(v) AS s FROM amounts WHERE 1 = 0")
  549. .fetch_one(&pool)
  550. .await
  551. .unwrap();
  552. assert_eq!(decoded(&row.try_get::<Vec<u8>, _>("s").unwrap()), 0);
  553. }
  554. /// The aggregate raises rather than wrapping. This is the property that makes
  555. /// summing in SQL as safe as `Cent::checked_sum`.
  556. #[tokio::test]
  557. async fn i128_sum_overflows_loudly() {
  558. let pool = new_pool().await;
  559. sqlx::query("CREATE TABLE amounts (v BLOB NOT NULL)")
  560. .execute(&pool)
  561. .await
  562. .unwrap();
  563. for _ in 0..2 {
  564. sqlx::query("INSERT INTO amounts (v) VALUES ($1)")
  565. .bind(encoded(i128::MAX))
  566. .execute(&pool)
  567. .await
  568. .unwrap();
  569. }
  570. let err = match sqlx::query("SELECT kuatia_i128_sum(v) AS s FROM amounts")
  571. .fetch_one(&pool)
  572. .await
  573. {
  574. Ok(_) => panic!("summing past i128::MAX should fail"),
  575. Err(e) => e.to_string(),
  576. };
  577. assert!(err.contains("i128"), "{err}");
  578. }
  579. /// A value that is not a 16-byte amount fails the statement instead of being
  580. /// skipped, so a corrupt row can never silently change a balance.
  581. #[tokio::test]
  582. async fn i128_sum_rejects_non_amount() {
  583. let pool = new_pool().await;
  584. let err = match sqlx::query("SELECT kuatia_i128_sum(x) AS s FROM (SELECT 'abc' AS x)")
  585. .fetch_one(&pool)
  586. .await
  587. {
  588. Ok(_) => panic!("a text argument should fail"),
  589. Err(e) => e.to_string(),
  590. };
  591. assert!(err.contains("16-byte"), "{err}");
  592. }
  593. /// The storage encoding is order-preserving, so SQLite's byte-wise BLOB
  594. /// comparison orders amounts numerically. This is what the text columns could
  595. /// not do (ADR-0011) and the reason the encoding flips the sign bit.
  596. #[tokio::test]
  597. async fn blob_order_matches_numeric_order() {
  598. let pool = new_pool().await;
  599. sqlx::query("CREATE TABLE amounts (v BLOB NOT NULL)")
  600. .execute(&pool)
  601. .await
  602. .unwrap();
  603. for v in [7i128, -9, 0, i128::MAX, i128::MIN, -1, 1] {
  604. sqlx::query("INSERT INTO amounts (v) VALUES ($1)")
  605. .bind(encoded(v))
  606. .execute(&pool)
  607. .await
  608. .unwrap();
  609. }
  610. let ordered: Vec<i128> =
  611. sqlx::query("SELECT kuatia_i128_to_text(v) AS t FROM amounts ORDER BY v")
  612. .fetch_all(&pool)
  613. .await
  614. .unwrap()
  615. .iter()
  616. .map(|r| r.try_get::<String, _>("t").unwrap().parse().unwrap())
  617. .collect();
  618. let mut expected = ordered.clone();
  619. expected.sort();
  620. assert_eq!(ordered, expected);
  621. assert_eq!(ordered.first(), Some(&i128::MIN));
  622. assert_eq!(ordered.last(), Some(&i128::MAX));
  623. }
  624. /// Amounts are stored at full i128 width, so a value past the i64 backing
  625. /// round-trips through the store under the `i128` feature.
  626. #[cfg(feature = "i128")]
  627. #[tokio::test]
  628. async fn value_beyond_i64_round_trips() {
  629. use std::str::FromStr;
  630. let store = new_store().await;
  631. let value = Cent::from_str("170141183460469231731687303715884105727").unwrap();
  632. let posting = Posting::new(
  633. PostingId {
  634. transfer: TransferId([0x5c; 32]),
  635. index: 0,
  636. },
  637. AccountId::new(1),
  638. AssetId::new(1),
  639. value,
  640. );
  641. seed_live(&store, 0x5c, std::slice::from_ref(&posting)).await;
  642. let got = store.get_postings(&[posting.id]).await.unwrap();
  643. assert_eq!(got[0].value, value);
  644. assert_eq!(
  645. store
  646. .live_balance(&AccountId::new(1), &AssetId::new(1))
  647. .await
  648. .unwrap(),
  649. value
  650. );
  651. }
  652. /// The 013 migration adds the value-date column, and an existing row gets NULL:
  653. /// an entry booked before the column existed was valued the day it was booked.
  654. #[tokio::test]
  655. async fn migration_013_adds_value_date_as_null_for_existing_rows() {
  656. let pool = new_pool().await;
  657. // Post-012 shape: transfers without a value date.
  658. 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)")
  659. .execute(&pool)
  660. .await
  661. .unwrap();
  662. sqlx::query("INSERT INTO transfers (id, transfer, receipt, created_at, book) VALUES ('aa', '{}', '{}', 5, 0)")
  663. .execute(&pool)
  664. .await
  665. .unwrap();
  666. sqlx::query("CREATE TABLE _migrations (name TEXT PRIMARY KEY)")
  667. .execute(&pool)
  668. .await
  669. .unwrap();
  670. for m in [
  671. "001_init",
  672. "002_subaccounts",
  673. "003_drop_user_data",
  674. "004_index_tables",
  675. "005_account_head",
  676. "006_drop_policy",
  677. "007_balance_projection",
  678. "008_live_postings",
  679. "009_saga_kind",
  680. "010_drop_sagas",
  681. "011_native_amounts",
  682. "012_drop_reservation",
  683. ] {
  684. sqlx::query("INSERT INTO _migrations (name) VALUES ($1)")
  685. .bind(m)
  686. .execute(&pool)
  687. .await
  688. .unwrap();
  689. }
  690. SqlStore::new(pool.clone()).migrate().await.unwrap();
  691. let row = sqlx::query("SELECT value_date FROM transfers WHERE id = 'aa'")
  692. .fetch_one(&pool)
  693. .await
  694. .unwrap();
  695. assert!(
  696. row.try_get::<Option<i64>, _>("value_date")
  697. .unwrap()
  698. .is_none(),
  699. "an entry booked before the column existed carries no value date"
  700. );
  701. }
  702. /// The value-date window is a SQL predicate, not a filter applied after loading,
  703. /// so it has to behave the same as the in-memory backend: an entry with no value
  704. /// date sits outside an explicit window rather than inside every one.
  705. #[tokio::test]
  706. async fn value_date_window_filters_in_sql() {
  707. let pool = new_pool().await;
  708. let store = SqlStore::new(pool.clone());
  709. store.migrate().await.unwrap();
  710. store
  711. .create_account(Account::new(AccountId::new(1)))
  712. .await
  713. .unwrap();
  714. for (tag, day) in [(1u8, Some(18u32)), (2, Some(20)), (3, Some(22)), (4, None)] {
  715. let tid = TransferId([tag; 32]);
  716. let value_date = day.map(|d| ValueDate::new(2026, 11, d).unwrap());
  717. let mut builder = EnvelopeBuilder::new().creates(vec![NewPosting {
  718. owner: AccountId::new(1),
  719. asset: AssetId::new(1),
  720. value: Cent::from(10),
  721. payer: None,
  722. }]);
  723. if let Some(date) = value_date {
  724. builder = builder.value_date(date);
  725. }
  726. let envelope = builder.build();
  727. let create = vec![Posting::new(
  728. PostingId {
  729. transfer: tid,
  730. index: 0,
  731. },
  732. AccountId::new(1),
  733. AssetId::new(1),
  734. Cent::from(10),
  735. )];
  736. let involved = [AccountId::new(1)];
  737. let outcome = store
  738. .commit_envelope(CommitRequest {
  739. transfer_id: tid,
  740. consume: &[],
  741. create: &create,
  742. record: TransferRecord {
  743. envelope,
  744. receipt: Receipt { transfer_id: tid },
  745. created_at: 1000,
  746. },
  747. involved: &involved,
  748. event: LedgerEvent {
  749. seq: 0,
  750. timestamp: 1000,
  751. kind: LedgerEventKind::TransferCommitted { transfer_id: tid },
  752. },
  753. })
  754. .await
  755. .unwrap();
  756. assert!(matches!(outcome, CommitOutcome::Committed(_)));
  757. }
  758. let page = store
  759. .query_transfers(&TransferQuery {
  760. account: Some(1),
  761. from_value_date: Some(ValueDate::new(2026, 11, 19).unwrap()),
  762. to_value_date: Some(ValueDate::new(2026, 11, 22).unwrap()),
  763. ..Default::default()
  764. })
  765. .await
  766. .unwrap();
  767. assert_eq!(page.total, 1, "only the entry valued on the 20th");
  768. assert_eq!(
  769. page.items[0].envelope.value_date(),
  770. Some(ValueDate::new(2026, 11, 20).unwrap())
  771. );
  772. // The column is written at commit, so the database can answer without
  773. // reading the envelope JSON back.
  774. let row = sqlx::query("SELECT COUNT(*) AS n FROM transfers WHERE value_date IS NULL")
  775. .fetch_one(&pool)
  776. .await
  777. .unwrap();
  778. assert_eq!(row.try_get::<i64, _>("n").unwrap(), 1);
  779. }
  780. /// The 012 migration drops the reservation column and leaves every live row
  781. /// live, including one that still carried a token: it was never consumed, so it
  782. /// must stay spendable and keep counting toward the balance.
  783. #[tokio::test]
  784. async fn migration_012_drops_reservation_and_keeps_rows_live() {
  785. let pool = new_pool().await;
  786. // Post-011 shape: native blob amounts, reservation column still present.
  787. for ddl in [
  788. "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))",
  789. "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))",
  790. ] {
  791. sqlx::query(ddl).execute(&pool).await.unwrap();
  792. }
  793. for (tid, value, reservation) in [("aa", 100i128, None), ("bb", 250i128, Some(77i64))] {
  794. sqlx::query("INSERT INTO live_postings (transfer_id, idx, owner, subaccount, asset, value, reservation) VALUES ($1, 0, 1, 0, 1, $2, $3)")
  795. .bind(tid)
  796. .bind(encoded(value))
  797. .bind(reservation)
  798. .execute(&pool)
  799. .await
  800. .unwrap();
  801. }
  802. // Record every migration except 012 as applied so migrate() runs only 012.
  803. sqlx::query("CREATE TABLE _migrations (name TEXT PRIMARY KEY)")
  804. .execute(&pool)
  805. .await
  806. .unwrap();
  807. for m in [
  808. "001_init",
  809. "002_subaccounts",
  810. "003_drop_user_data",
  811. "004_index_tables",
  812. "005_account_head",
  813. "006_drop_policy",
  814. "007_balance_projection",
  815. "008_live_postings",
  816. "009_saga_kind",
  817. "010_drop_sagas",
  818. "011_native_amounts",
  819. "013_value_date",
  820. ] {
  821. sqlx::query("INSERT INTO _migrations (name) VALUES ($1)")
  822. .bind(m)
  823. .execute(&pool)
  824. .await
  825. .unwrap();
  826. }
  827. let store = SqlStore::new(pool.clone());
  828. store.migrate().await.unwrap();
  829. assert!(
  830. sqlx::query("SELECT reservation FROM live_postings")
  831. .fetch_all(&pool)
  832. .await
  833. .is_err(),
  834. "the reservation column is gone"
  835. );
  836. // Both rows are still live, and the previously reserved one still sums in.
  837. let row = sqlx::query("SELECT COUNT(*) AS n, kuatia_i128_sum(value) AS s FROM live_postings")
  838. .fetch_one(&pool)
  839. .await
  840. .unwrap();
  841. assert_eq!(row.try_get::<i64, _>("n").unwrap(), 2);
  842. assert_eq!(decoded(&row.try_get::<Vec<u8>, _>("s").unwrap()), 350);
  843. }
  844. /// The 011 migration rewrites the existing text amounts into the native blob
  845. /// encoding, keeping their values (including negatives) and the rest of the row.
  846. #[tokio::test]
  847. async fn migration_011_converts_text_amounts() {
  848. let pool = new_pool().await;
  849. // Post-010 shape: money columns are still TEXT.
  850. for ddl in [
  851. "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))",
  852. "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))",
  853. "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))",
  854. "INSERT INTO postings (transfer_id, idx, owner, subaccount, asset, value) VALUES ('aa', 0, 1, 0, 1, '100')",
  855. "INSERT INTO postings (transfer_id, idx, owner, subaccount, asset, value) VALUES ('bb', 0, 1, 0, 1, '-250')",
  856. "INSERT INTO live_postings (transfer_id, idx, owner, subaccount, asset, value, reservation) VALUES ('aa', 0, 1, 0, 1, '100', 77)",
  857. "INSERT INTO balance_projection (id, account, subaccount, asset, balance, watermark) VALUES (1, 1, 0, 1, '-150', 5)",
  858. ] {
  859. sqlx::query(ddl).execute(&pool).await.unwrap();
  860. }
  861. // Record every migration except 011 as applied so migrate() runs only 011.
  862. sqlx::query("CREATE TABLE _migrations (name TEXT PRIMARY KEY)")
  863. .execute(&pool)
  864. .await
  865. .unwrap();
  866. for m in [
  867. "001_init",
  868. "002_subaccounts",
  869. "003_drop_user_data",
  870. "004_index_tables",
  871. "005_account_head",
  872. "006_drop_policy",
  873. "007_balance_projection",
  874. "008_live_postings",
  875. "009_saga_kind",
  876. "010_drop_sagas",
  877. "012_drop_reservation",
  878. "013_value_date",
  879. ] {
  880. sqlx::query("INSERT INTO _migrations (name) VALUES ($1)")
  881. .bind(m)
  882. .execute(&pool)
  883. .await
  884. .unwrap();
  885. }
  886. let store = SqlStore::new(pool.clone());
  887. store.migrate().await.unwrap();
  888. let rows = sqlx::query(
  889. "SELECT transfer_id, typeof(value) AS t, kuatia_i128_to_text(value) AS v FROM postings ORDER BY transfer_id",
  890. )
  891. .fetch_all(&pool)
  892. .await
  893. .unwrap();
  894. let got: Vec<(String, String, String)> = rows
  895. .iter()
  896. .map(|r| {
  897. (
  898. r.try_get("transfer_id").unwrap(),
  899. r.try_get("t").unwrap(),
  900. r.try_get("v").unwrap(),
  901. )
  902. })
  903. .collect();
  904. assert_eq!(
  905. got,
  906. vec![
  907. ("aa".to_string(), "blob".to_string(), "100".to_string()),
  908. ("bb".to_string(), "blob".to_string(), "-250".to_string()),
  909. ]
  910. );
  911. // The rest of the row survives, and the summing path reads the new column.
  912. let row = sqlx::query("SELECT reservation, kuatia_i128_sum(value) AS s FROM live_postings")
  913. .fetch_one(&pool)
  914. .await
  915. .unwrap();
  916. assert_eq!(row.try_get::<i64, _>("reservation").unwrap(), 77);
  917. assert_eq!(decoded(&row.try_get::<Vec<u8>, _>("s").unwrap()), 100);
  918. let row =
  919. sqlx::query("SELECT kuatia_i128_to_text(balance) AS b, watermark FROM balance_projection")
  920. .fetch_one(&pool)
  921. .await
  922. .unwrap();
  923. assert_eq!(row.try_get::<String, _>("b").unwrap(), "-150");
  924. assert_eq!(row.try_get::<i64, _>("watermark").unwrap(), 5);
  925. }