sqlite.rs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  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. sqlx::any::install_default_drivers();
  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 column holds opaque binary. A content-addressed
  22. /// id is stored as lower-case hex text, and a structured payload as readable
  23. /// JSON text, so a row can be audited in a plain SQL client.
  24. #[tokio::test]
  25. async fn columns_store_hex_ids_and_json_text() {
  26. let pool = new_pool().await;
  27. let store = SqlStore::new(pool.clone());
  28. store.migrate().await.unwrap();
  29. let account = Account {
  30. id: AccountId::new(1),
  31. version: 1,
  32. flags: AccountFlags::DEBIT_MUST_NOT_EXCEED_CREDIT,
  33. book: BookId(0),
  34. metadata: std::collections::BTreeMap::new(),
  35. };
  36. store.create_account(account).await.unwrap();
  37. let tid = EnvelopeId([0xab; 32]);
  38. let posting = Posting::new(
  39. PostingId {
  40. transfer: tid,
  41. index: 0,
  42. },
  43. AccountId::new(1),
  44. AssetId::new(1),
  45. Cent::from(100),
  46. );
  47. store.insert_postings(&[posting]).await.unwrap();
  48. // The 32-byte transfer id is stored as its 64-char lower-case hex form.
  49. let row = sqlx::query("SELECT transfer_id FROM postings")
  50. .fetch_one(&pool)
  51. .await
  52. .unwrap();
  53. let transfer_id: String = row.try_get("transfer_id").unwrap();
  54. assert_eq!(transfer_id, "ab".repeat(32));
  55. // The account payload is readable JSON text, not a blob.
  56. let row = sqlx::query("SELECT metadata FROM accounts")
  57. .fetch_one(&pool)
  58. .await
  59. .unwrap();
  60. let metadata: String = row.try_get("metadata").unwrap();
  61. assert!(
  62. serde_json::from_str::<serde_json::Value>(&metadata).is_ok(),
  63. "metadata should be JSON text, got: {metadata}"
  64. );
  65. }
  66. /// The 002 migration adds the subaccount column and a subaccount account/posting
  67. /// round-trips through the schema, kept distinct from the main account.
  68. #[tokio::test]
  69. async fn subaccount_columns_round_trip() {
  70. let store = new_store().await;
  71. let sub = AccountId::with_sub(1, 7);
  72. store
  73. .create_account(Account::debit_must_not_exceed_credit(sub))
  74. .await
  75. .unwrap();
  76. // The main account (1, 0) is a separate record.
  77. store
  78. .create_account(Account::debit_must_not_exceed_credit(AccountId::new(1)))
  79. .await
  80. .unwrap();
  81. let got = store.get_account(&sub).await.unwrap();
  82. assert_eq!(got.id, sub);
  83. let posting = Posting::new(
  84. PostingId {
  85. transfer: EnvelopeId([0xcd; 32]),
  86. index: 0,
  87. },
  88. sub,
  89. AssetId::new(1),
  90. Cent::from(500),
  91. );
  92. store.insert_postings(&[posting]).await.unwrap();
  93. // Filtering by the subaccount returns it; the main account holds nothing.
  94. let by_sub = store
  95. .get_postings_by_account(1, Some(7), None, PostingFilter::All)
  96. .await
  97. .unwrap();
  98. assert_eq!(by_sub.len(), 1);
  99. assert_eq!(by_sub[0].owner, sub);
  100. let by_main = store
  101. .get_postings_by_account(1, Some(0), None, PostingFilter::All)
  102. .await
  103. .unwrap();
  104. assert!(by_main.is_empty());
  105. }
  106. /// A database created under 001 (no subaccount column) upgrades in place: the
  107. /// 002 migration rebuilds the tables and existing rows default to subaccount 0,
  108. /// the main account.
  109. #[tokio::test]
  110. async fn migration_upgrades_existing_rows_to_main_account() {
  111. let pool = new_pool().await;
  112. // Pre-002 schema: the tables 002 rebuilds, in their old (no-subaccount) shape.
  113. sqlx::query(
  114. "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))",
  115. )
  116. .execute(&pool)
  117. .await
  118. .unwrap();
  119. sqlx::query(
  120. "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))",
  121. )
  122. .execute(&pool)
  123. .await
  124. .unwrap();
  125. sqlx::query("CREATE INDEX idx_postings_owner ON postings(owner, asset, status)")
  126. .execute(&pool)
  127. .await
  128. .unwrap();
  129. sqlx::query(
  130. "CREATE TABLE transfer_accounts (transfer_id TEXT NOT NULL, account_id BIGINT NOT NULL, PRIMARY KEY (transfer_id, account_id))",
  131. )
  132. .execute(&pool)
  133. .await
  134. .unwrap();
  135. sqlx::query("CREATE INDEX idx_xfer_acct ON transfer_accounts(account_id)")
  136. .execute(&pool)
  137. .await
  138. .unwrap();
  139. // The sagas table has existed since 001; seed it so the 009 ALTER (add the
  140. // kind column) has a table to run against on this full-chain upgrade.
  141. sqlx::query("CREATE TABLE sagas (id BIGINT PRIMARY KEY, data TEXT NOT NULL)")
  142. .execute(&pool)
  143. .await
  144. .unwrap();
  145. // Legacy 001/002 schema carried a user_data JSON column; the 003 migration
  146. // drops it. Seed it with the value the old UserData type serialized to.
  147. let user_data = r#"{"d128":0,"d64":0,"d32":0}"#.to_string();
  148. let metadata =
  149. serde_json::to_string(&std::collections::BTreeMap::<String, String>::new()).unwrap();
  150. sqlx::query(
  151. "INSERT INTO accounts (id, version, policy, flags, book, user_data, metadata) VALUES (5, 1, '\"NoOverdraft\"', 0, 0, $1, $2)",
  152. )
  153. .bind(user_data)
  154. .bind(metadata)
  155. .execute(&pool)
  156. .await
  157. .unwrap();
  158. // Record 001 as applied so migrate() only runs 002 against this schema.
  159. sqlx::query("CREATE TABLE _migrations (name TEXT PRIMARY KEY)")
  160. .execute(&pool)
  161. .await
  162. .unwrap();
  163. sqlx::query("INSERT INTO _migrations (name) VALUES ('001_init')")
  164. .execute(&pool)
  165. .await
  166. .unwrap();
  167. let store = SqlStore::new(pool);
  168. store.migrate().await.unwrap();
  169. // The pre-existing account is now the main account (subaccount 0).
  170. let got = store.get_account(&AccountId::new(5)).await.unwrap();
  171. assert_eq!(got.id, AccountId::new(5));
  172. assert!(got.id.is_main());
  173. }
  174. /// The 004 migration splits lifecycle state out of `postings` into the two
  175. /// id-only index tables: an active (status 0) posting is backfilled into
  176. /// `active_postings`, a reserved (status 1) posting into `reserved_postings`
  177. /// with its token, and the `status` column is dropped from `postings`.
  178. #[tokio::test]
  179. async fn migration_004_backfills_index_tables() {
  180. let pool = new_pool().await;
  181. // Pre-004 postings schema (the shape 001->003 leave it): status + reservation.
  182. sqlx::query(
  183. "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))",
  184. )
  185. .execute(&pool)
  186. .await
  187. .unwrap();
  188. // One active (status 0) and one reserved (status 1, reservation 77) posting.
  189. sqlx::query("INSERT INTO postings (transfer_id, idx, owner, subaccount, asset, value, status, reservation) VALUES ('aa', 0, 1, 0, 1, '100', 0, NULL)")
  190. .execute(&pool)
  191. .await
  192. .unwrap();
  193. sqlx::query("INSERT INTO postings (transfer_id, idx, owner, subaccount, asset, value, status, reservation) VALUES ('bb', 0, 1, 0, 1, '200', 1, 77)")
  194. .execute(&pool)
  195. .await
  196. .unwrap();
  197. // A post-003 DB also has the accounts table (empty here).
  198. sqlx::query(
  199. "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))",
  200. )
  201. .execute(&pool)
  202. .await
  203. .unwrap();
  204. // Record every migration except 004 as applied so migrate() runs only 004,
  205. // isolating its backfill. In particular 008 (which merges the index tables
  206. // into `live_postings`) is pinned as applied so it does not run and clobber
  207. // the active/reserved tables this test inspects.
  208. sqlx::query("CREATE TABLE _migrations (name TEXT PRIMARY KEY)")
  209. .execute(&pool)
  210. .await
  211. .unwrap();
  212. for m in [
  213. "001_init",
  214. "002_subaccounts",
  215. "003_drop_user_data",
  216. "005_account_head",
  217. "006_drop_policy",
  218. "007_balance_projection",
  219. "008_live_postings",
  220. "009_saga_kind",
  221. ] {
  222. sqlx::query("INSERT INTO _migrations (name) VALUES ($1)")
  223. .bind(m)
  224. .execute(&pool)
  225. .await
  226. .unwrap();
  227. }
  228. let store = SqlStore::new(pool.clone());
  229. store.migrate().await.unwrap();
  230. // The active posting is now in active_postings, carrying a full row copy.
  231. let active = sqlx::query("SELECT transfer_id, owner, asset, value FROM active_postings")
  232. .fetch_all(&pool)
  233. .await
  234. .unwrap();
  235. assert_eq!(active.len(), 1);
  236. let a_tid: String = active[0].try_get("transfer_id").unwrap();
  237. let a_owner: i64 = active[0].try_get("owner").unwrap();
  238. let a_value: String = active[0].try_get("value").unwrap();
  239. assert_eq!(a_tid, "aa");
  240. assert_eq!(a_owner, 1);
  241. assert_eq!(a_value, "100");
  242. // The reserved posting is in reserved_postings with its data copy and token.
  243. let reserved = sqlx::query("SELECT transfer_id, value, reservation FROM reserved_postings")
  244. .fetch_all(&pool)
  245. .await
  246. .unwrap();
  247. assert_eq!(reserved.len(), 1);
  248. let r_tid: String = reserved[0].try_get("transfer_id").unwrap();
  249. let r_value: String = reserved[0].try_get("value").unwrap();
  250. let r_res: i64 = reserved[0].try_get("reservation").unwrap();
  251. assert_eq!(r_tid, "bb");
  252. assert_eq!(r_value, "200");
  253. assert_eq!(r_res, 77);
  254. // Both immutable rows survive; the status column is gone.
  255. let all = sqlx::query("SELECT transfer_id FROM postings")
  256. .fetch_all(&pool)
  257. .await
  258. .unwrap();
  259. assert_eq!(all.len(), 2);
  260. assert!(
  261. sqlx::query("SELECT status FROM postings")
  262. .fetch_all(&pool)
  263. .await
  264. .is_err()
  265. );
  266. }
  267. /// The 005 migration backfills `account_head` with the current (highest)
  268. /// version of each account, so a subsequent read hits one row per account
  269. /// without scanning the version history.
  270. #[tokio::test]
  271. async fn migration_005_backfills_account_head() {
  272. let pool = new_pool().await;
  273. // Pre-005 accounts schema (post-004 shape) with a versioned history:
  274. // account 1 has three versions, account 2 has one.
  275. sqlx::query(
  276. "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))",
  277. )
  278. .execute(&pool)
  279. .await
  280. .unwrap();
  281. for (id, version) in [(1, 1), (1, 2), (1, 3), (2, 1)] {
  282. sqlx::query("INSERT INTO accounts (id, subaccount, version, policy, flags, book, metadata) VALUES ($1, 0, $2, '\"NoOverdraft\"', 0, 0, '{}')")
  283. .bind(id as i64)
  284. .bind(version as i64)
  285. .execute(&pool)
  286. .await
  287. .unwrap();
  288. }
  289. // Record every migration except 005 as applied so migrate() runs only 005.
  290. // 008 is pinned as applied so it does not run against a DB whose 004 index
  291. // tables were never created.
  292. sqlx::query("CREATE TABLE _migrations (name TEXT PRIMARY KEY)")
  293. .execute(&pool)
  294. .await
  295. .unwrap();
  296. for m in [
  297. "001_init",
  298. "002_subaccounts",
  299. "003_drop_user_data",
  300. "004_index_tables",
  301. "006_drop_policy",
  302. "007_balance_projection",
  303. "008_live_postings",
  304. "009_saga_kind",
  305. ] {
  306. sqlx::query("INSERT INTO _migrations (name) VALUES ($1)")
  307. .bind(m)
  308. .execute(&pool)
  309. .await
  310. .unwrap();
  311. }
  312. let store = SqlStore::new(pool.clone());
  313. store.migrate().await.unwrap();
  314. // One head per account, each pointing at the highest version.
  315. let mut heads: Vec<(i64, i64)> = sqlx::query("SELECT id, version FROM account_head")
  316. .fetch_all(&pool)
  317. .await
  318. .unwrap()
  319. .iter()
  320. .map(|r| (r.try_get("id").unwrap(), r.try_get("version").unwrap()))
  321. .collect();
  322. heads.sort();
  323. assert_eq!(heads, vec![(1, 3), (2, 1)]);
  324. // The store reads the current version through the head.
  325. let acct = store.get_account(&AccountId::new(1)).await.unwrap();
  326. assert_eq!(acct.version, 3);
  327. }
  328. /// The 008 migration merges the two index tables into one `live_postings`
  329. /// table: an active row is backfilled with `reservation` NULL, a reserved row
  330. /// keeps its token, and the old `active_postings`/`reserved_postings` tables are
  331. /// dropped.
  332. #[tokio::test]
  333. async fn migration_008_merges_live_postings() {
  334. let pool = new_pool().await;
  335. // Post-004 index tables with one active and one reserved posting.
  336. sqlx::query(
  337. "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))",
  338. )
  339. .execute(&pool)
  340. .await
  341. .unwrap();
  342. sqlx::query(
  343. "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))",
  344. )
  345. .execute(&pool)
  346. .await
  347. .unwrap();
  348. sqlx::query("INSERT INTO active_postings (transfer_id, idx, owner, subaccount, asset, value) VALUES ('aa', 0, 1, 0, 1, '100')")
  349. .execute(&pool)
  350. .await
  351. .unwrap();
  352. sqlx::query("INSERT INTO reserved_postings (transfer_id, idx, owner, subaccount, asset, value, reservation) VALUES ('bb', 0, 1, 0, 1, '200', 77)")
  353. .execute(&pool)
  354. .await
  355. .unwrap();
  356. // Record every migration except 008 as applied so migrate() runs only 008.
  357. sqlx::query("CREATE TABLE _migrations (name TEXT PRIMARY KEY)")
  358. .execute(&pool)
  359. .await
  360. .unwrap();
  361. for m in [
  362. "001_init",
  363. "002_subaccounts",
  364. "003_drop_user_data",
  365. "004_index_tables",
  366. "005_account_head",
  367. "006_drop_policy",
  368. "007_balance_projection",
  369. "009_saga_kind",
  370. ] {
  371. sqlx::query("INSERT INTO _migrations (name) VALUES ($1)")
  372. .bind(m)
  373. .execute(&pool)
  374. .await
  375. .unwrap();
  376. }
  377. let store = SqlStore::new(pool.clone());
  378. store.migrate().await.unwrap();
  379. // The active row lands with reservation NULL, the reserved row keeps its token.
  380. let mut rows: Vec<(String, Option<i64>)> =
  381. sqlx::query("SELECT transfer_id, reservation FROM live_postings")
  382. .fetch_all(&pool)
  383. .await
  384. .unwrap()
  385. .iter()
  386. .map(|r| {
  387. (
  388. r.try_get("transfer_id").unwrap(),
  389. r.try_get("reservation").unwrap(),
  390. )
  391. })
  392. .collect();
  393. rows.sort();
  394. assert_eq!(
  395. rows,
  396. vec![("aa".to_string(), None), ("bb".to_string(), Some(77))]
  397. );
  398. // The old index tables are gone.
  399. assert!(
  400. sqlx::query("SELECT 1 FROM active_postings")
  401. .fetch_all(&pool)
  402. .await
  403. .is_err()
  404. );
  405. assert!(
  406. sqlx::query("SELECT 1 FROM reserved_postings")
  407. .fetch_all(&pool)
  408. .await
  409. .is_err()
  410. );
  411. }
  412. /// migrate() is idempotent: running it repeatedly on the same DB is a no-op.
  413. #[tokio::test]
  414. async fn migrate_is_idempotent() {
  415. sqlx::any::install_default_drivers();
  416. let pool = sqlx::any::AnyPoolOptions::new()
  417. .max_connections(1)
  418. .connect("sqlite::memory:")
  419. .await
  420. .unwrap();
  421. let store = SqlStore::new(pool);
  422. store.migrate().await.unwrap();
  423. store.migrate().await.unwrap();
  424. store.migrate().await.unwrap();
  425. }
  426. /// The id-batch primitives chunk a large id set so it never exceeds the
  427. /// backend's bind-parameter limit (SQLite caps a statement at 32766 variables).
  428. /// A batch larger than one chunk must reserve, read, and deactivate every id
  429. /// exactly as a small one does.
  430. #[tokio::test]
  431. async fn id_batch_primitives_chunk_large_batches() {
  432. // Comfortably larger than the internal chunk size so the batch spans
  433. // multiple statements.
  434. const N: u16 = 9000;
  435. let store = new_store().await;
  436. let tid = EnvelopeId([0xcd; 32]);
  437. let postings: Vec<Posting> = (0..N)
  438. .map(|i| {
  439. Posting::new(
  440. PostingId {
  441. transfer: tid,
  442. index: i,
  443. },
  444. AccountId::new(1),
  445. AssetId::new(1),
  446. Cent::from(1),
  447. )
  448. })
  449. .collect();
  450. let ids: Vec<PostingId> = postings.iter().map(|p| p.id).collect();
  451. assert_eq!(
  452. store.insert_postings(&postings).await.unwrap(),
  453. u64::from(N)
  454. );
  455. // Reserve the whole batch in one call: every id is claimed across chunks.
  456. let rid = ReservationId::new(1);
  457. assert_eq!(
  458. store.reserve_postings(&ids, rid).await.unwrap(),
  459. u64::from(N)
  460. );
  461. // Reads span chunks and return every id.
  462. let states = store.get_posting_states(&ids).await.unwrap();
  463. assert_eq!(states.len(), N as usize);
  464. assert!(states.iter().all(|s| *s == PostingState::Reserved(rid)));
  465. assert_eq!(store.get_postings(&ids).await.unwrap().len(), N as usize);
  466. // Deactivating the whole batch spends every id.
  467. assert_eq!(
  468. store.deactivate_postings(&ids, Some(rid)).await.unwrap(),
  469. u64::from(N)
  470. );
  471. let after = store.get_posting_states(&ids).await.unwrap();
  472. assert!(after.iter().all(|s| *s == PostingState::Spent));
  473. }