sqlite.rs 28 KB

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