sqlite.rs 36 KB

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