sqlite.rs 30 KB

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