postgres.rs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. #![allow(missing_docs)]
  2. #![cfg(feature = "test-postgres")]
  3. //! PostgreSQL conformance run.
  4. //!
  5. //! The same `store_tests!` suite the SQLite backend passes, driven against a
  6. //! real PostgreSQL instance so the Postgres-only code paths (the `FOR UPDATE`
  7. //! row locks behind `lock_clause`, the `ON CONFLICT` upserts) are actually
  8. //! exercised. Point `DATABASE_URL` at a Postgres database to run it; the CI
  9. //! `Test (PostgreSQL)` job supplies one.
  10. //!
  11. //! Unlike `sqlite::memory:`, where every pool is its own fresh database, all
  12. //! tests here share one Postgres database and the conformance tests reuse fixed
  13. //! ids. Each store therefore gets its own uniquely-named schema, and the pool is
  14. //! pinned to a single connection so the session `search_path` set below persists
  15. //! for the store's whole lifetime.
  16. use std::sync::atomic::{AtomicU64, Ordering};
  17. use kuatia_storage::store::PostingStore;
  18. use kuatia_storage::store_tests::seed_live;
  19. use kuatia_storage_sql::SqlStore;
  20. use kuatia_types::*;
  21. use sqlx::{Any, Pool, Row};
  22. static SCHEMA_SEQ: AtomicU64 = AtomicU64::new(0);
  23. /// An amount of `asset` in minor units. These tests assert on ids and values,
  24. /// and an amount compares by asset id, so the metadata here is filler.
  25. fn money<V>(asset: AssetId, value: V) -> Amount
  26. where
  27. Amount: From<(V, std::sync::Arc<Asset>)>,
  28. {
  29. Amount::from((
  30. value,
  31. std::sync::Arc::new(Asset::new(asset, "TEST", "$", 2)),
  32. ))
  33. }
  34. async fn new_store() -> SqlStore {
  35. new_store_with_pool().await.0
  36. }
  37. async fn new_store_with_pool() -> (SqlStore, Pool<Any>) {
  38. kuatia_storage_sql::install_drivers().expect("install drivers");
  39. let url = std::env::var("DATABASE_URL")
  40. .expect("DATABASE_URL must point at a PostgreSQL instance for this suite");
  41. // One connection per store so the session-level `search_path` set below
  42. // survives across every query the store issues.
  43. let pool: Pool<Any> = sqlx::any::AnyPoolOptions::new()
  44. .max_connections(1)
  45. .connect(&url)
  46. .await
  47. .unwrap();
  48. // Isolate each store in its own schema: the conformance tests reuse fixed
  49. // ids, so a shared schema would collide across tests.
  50. let n = SCHEMA_SEQ.fetch_add(1, Ordering::Relaxed);
  51. let schema = format!("conformance_{n}");
  52. for stmt in [
  53. format!("DROP SCHEMA IF EXISTS {schema} CASCADE"),
  54. format!("CREATE SCHEMA {schema}"),
  55. format!("SET search_path TO {schema}"),
  56. ] {
  57. sqlx::query(&stmt).execute(&pool).await.unwrap();
  58. }
  59. let store = SqlStore::new(pool.clone());
  60. store.migrate().await.unwrap();
  61. (store, pool)
  62. }
  63. kuatia_storage::store_tests!(new_store);
  64. /// Amounts are stored as native `NUMERIC`, not text, and round-trip through the
  65. /// store. The type assertion is the point: under `sqlx::Any` an uncast
  66. /// `NUMERIC` fails the whole row, so this also proves every money `SELECT`
  67. /// goes through `Dialect::money_read` (ADR-0024).
  68. #[tokio::test]
  69. async fn amount_columns_are_numeric() {
  70. let (store, pool) = new_store_with_pool().await;
  71. let posting = Posting::new(
  72. PostingId {
  73. transfer: TransferId([0x3f; 32]),
  74. index: 0,
  75. },
  76. AccountId::new(1),
  77. money(AssetId::new(1), -4321),
  78. );
  79. seed_live(&store, 0x3f, std::slice::from_ref(&posting)).await;
  80. let got = store.get_postings(&[posting.id]).await.unwrap();
  81. assert_eq!(got[0].amount.minor_units(), -4321);
  82. assert_eq!(
  83. store
  84. .live_balance(&AccountId::new(1), &AssetId::new(1))
  85. .await
  86. .unwrap()
  87. .minor_units(),
  88. -4321
  89. );
  90. for (table, column) in [
  91. ("postings", "value"),
  92. ("live_postings", "value"),
  93. ("balance_projection", "balance"),
  94. ] {
  95. let row = sqlx::query(
  96. "SELECT data_type FROM information_schema.columns \
  97. WHERE table_schema = current_schema() AND table_name = $1 AND column_name = $2",
  98. )
  99. .bind(table)
  100. .bind(column)
  101. .fetch_one(&pool)
  102. .await
  103. .unwrap();
  104. assert_eq!(
  105. row.try_get::<String, _>("data_type").unwrap(),
  106. "numeric",
  107. "{table}.{column}"
  108. );
  109. }
  110. }
  111. /// The 013 migration adds the value-date column, and an existing row gets NULL:
  112. /// an entry booked before the column existed was valued the day it was booked.
  113. #[tokio::test]
  114. async fn migration_013_adds_value_date_as_null_for_existing_rows() {
  115. let (_store, pool) = new_store_with_pool().await;
  116. for stmt in [
  117. "ALTER TABLE transfers DROP COLUMN value_date",
  118. "INSERT INTO transfers (id, transfer, receipt, created_at, book) VALUES ('aa', '{}', '{}', 5, 0)",
  119. "DELETE FROM _migrations WHERE name = '013_value_date'",
  120. ] {
  121. sqlx::query(stmt).execute(&pool).await.unwrap();
  122. }
  123. let store = SqlStore::new(pool.clone());
  124. store.migrate().await.unwrap();
  125. let row = sqlx::query("SELECT value_date FROM transfers WHERE id = 'aa'")
  126. .fetch_one(&pool)
  127. .await
  128. .unwrap();
  129. assert!(
  130. row.try_get::<Option<i64>, _>("value_date")
  131. .unwrap()
  132. .is_none(),
  133. "an entry booked before the column existed carries no value date"
  134. );
  135. }
  136. /// The 012 migration drops the reservation column and leaves every live row
  137. /// live, including one that still carried a token: it was never consumed, so it
  138. /// must stay spendable and keep counting toward the balance.
  139. #[tokio::test]
  140. async fn migration_012_drops_reservation_and_keeps_rows_live() {
  141. let (_store, pool) = new_store_with_pool().await;
  142. // Put the column back, with a reserved row in it, then replay 012 alone.
  143. for stmt in [
  144. "ALTER TABLE live_postings ADD COLUMN reservation BIGINT",
  145. "INSERT INTO live_postings (transfer_id, idx, owner, subaccount, asset, value, reservation) VALUES ('aa', 0, 1, 0, 1, 100, NULL)",
  146. "INSERT INTO live_postings (transfer_id, idx, owner, subaccount, asset, value, reservation) VALUES ('bb', 0, 1, 0, 1, 250, 77)",
  147. "DELETE FROM _migrations WHERE name = '012_drop_reservation'",
  148. ] {
  149. sqlx::query(stmt).execute(&pool).await.unwrap();
  150. }
  151. let store = SqlStore::new(pool.clone());
  152. store.migrate().await.unwrap();
  153. let columns = sqlx::query(
  154. "SELECT column_name FROM information_schema.columns \
  155. WHERE table_schema = current_schema() AND table_name = 'live_postings' \
  156. AND column_name = 'reservation'",
  157. )
  158. .fetch_all(&pool)
  159. .await
  160. .unwrap();
  161. assert!(columns.is_empty(), "the reservation column is gone");
  162. // Both rows are still live, and the previously reserved one still sums in.
  163. let row = sqlx::query("SELECT COUNT(*) AS n, CAST(SUM(value) AS TEXT) AS s FROM live_postings")
  164. .fetch_one(&pool)
  165. .await
  166. .unwrap();
  167. assert_eq!(row.try_get::<i64, _>("n").unwrap(), 2);
  168. assert_eq!(row.try_get::<String, _>("s").unwrap(), "350");
  169. }
  170. /// The 011 migration rewrites the existing text amounts into `NUMERIC`, keeping
  171. /// their values (including negatives).
  172. #[tokio::test]
  173. async fn migration_011_converts_text_amounts() {
  174. let (_store, pool) = new_store_with_pool().await;
  175. // Roll the money columns back to their pre-011 text form, with rows in
  176. // them, then replay 011 alone.
  177. for stmt in [
  178. "ALTER TABLE postings ALTER COLUMN value TYPE TEXT USING value::text",
  179. "ALTER TABLE live_postings ALTER COLUMN value TYPE TEXT USING value::text",
  180. "ALTER TABLE balance_projection ALTER COLUMN balance TYPE TEXT USING balance::text",
  181. "INSERT INTO postings (transfer_id, idx, owner, subaccount, asset, value) VALUES ('aa', 0, 1, 0, 1, '100')",
  182. "INSERT INTO postings (transfer_id, idx, owner, subaccount, asset, value) VALUES ('bb', 0, 1, 0, 1, '-250')",
  183. "DELETE FROM _migrations WHERE name = '011_native_amounts'",
  184. ] {
  185. sqlx::query(stmt).execute(&pool).await.unwrap();
  186. }
  187. let store = SqlStore::new(pool.clone());
  188. store.migrate().await.unwrap();
  189. let rows = sqlx::query("SELECT CAST(value AS TEXT) AS v FROM postings ORDER BY transfer_id")
  190. .fetch_all(&pool)
  191. .await
  192. .unwrap();
  193. let got: Vec<String> = rows.iter().map(|r| r.try_get("v").unwrap()).collect();
  194. assert_eq!(got, vec!["100".to_string(), "-250".to_string()]);
  195. let row = sqlx::query(
  196. "SELECT data_type FROM information_schema.columns \
  197. WHERE table_schema = current_schema() AND table_name = 'postings' AND column_name = 'value'",
  198. )
  199. .fetch_one(&pool)
  200. .await
  201. .unwrap();
  202. assert_eq!(row.try_get::<String, _>("data_type").unwrap(), "numeric");
  203. }