postgres.rs 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  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. async fn new_store() -> SqlStore {
  24. new_store_with_pool().await.0
  25. }
  26. async fn new_store_with_pool() -> (SqlStore, Pool<Any>) {
  27. kuatia_storage_sql::install_drivers().expect("install drivers");
  28. let url = std::env::var("DATABASE_URL")
  29. .expect("DATABASE_URL must point at a PostgreSQL instance for this suite");
  30. // One connection per store so the session-level `search_path` set below
  31. // survives across every query the store issues.
  32. let pool: Pool<Any> = sqlx::any::AnyPoolOptions::new()
  33. .max_connections(1)
  34. .connect(&url)
  35. .await
  36. .unwrap();
  37. // Isolate each store in its own schema: the conformance tests reuse fixed
  38. // ids, so a shared schema would collide across tests.
  39. let n = SCHEMA_SEQ.fetch_add(1, Ordering::Relaxed);
  40. let schema = format!("conformance_{n}");
  41. for stmt in [
  42. format!("DROP SCHEMA IF EXISTS {schema} CASCADE"),
  43. format!("CREATE SCHEMA {schema}"),
  44. format!("SET search_path TO {schema}"),
  45. ] {
  46. sqlx::query(&stmt).execute(&pool).await.unwrap();
  47. }
  48. let store = SqlStore::new(pool.clone());
  49. store.migrate().await.unwrap();
  50. (store, pool)
  51. }
  52. kuatia_storage::store_tests!(new_store);
  53. /// Amounts are stored as native `NUMERIC`, not text, and round-trip through the
  54. /// store. The type assertion is the point: under `sqlx::Any` an uncast
  55. /// `NUMERIC` fails the whole row, so this also proves every money `SELECT`
  56. /// goes through `Dialect::money_read` (ADR-0024).
  57. #[tokio::test]
  58. async fn amount_columns_are_numeric() {
  59. let (store, pool) = new_store_with_pool().await;
  60. let posting = Posting::new(
  61. PostingId {
  62. transfer: TransferId([0x3f; 32]),
  63. index: 0,
  64. },
  65. AccountId::new(1),
  66. AssetId::new(1),
  67. Cent::from(-4321),
  68. );
  69. seed_live(&store, 0x3f, std::slice::from_ref(&posting)).await;
  70. let got = store.get_postings(&[posting.id]).await.unwrap();
  71. assert_eq!(got[0].value, Cent::from(-4321));
  72. assert_eq!(
  73. store
  74. .live_balance(&AccountId::new(1), &AssetId::new(1))
  75. .await
  76. .unwrap(),
  77. Cent::from(-4321)
  78. );
  79. for (table, column) in [
  80. ("postings", "value"),
  81. ("live_postings", "value"),
  82. ("balance_projection", "balance"),
  83. ] {
  84. let row = sqlx::query(
  85. "SELECT data_type FROM information_schema.columns \
  86. WHERE table_schema = current_schema() AND table_name = $1 AND column_name = $2",
  87. )
  88. .bind(table)
  89. .bind(column)
  90. .fetch_one(&pool)
  91. .await
  92. .unwrap();
  93. assert_eq!(
  94. row.try_get::<String, _>("data_type").unwrap(),
  95. "numeric",
  96. "{table}.{column}"
  97. );
  98. }
  99. }
  100. /// The 012 migration drops the reservation column and leaves every live row
  101. /// live, including one that still carried a token: it was never consumed, so it
  102. /// must stay spendable and keep counting toward the balance.
  103. #[tokio::test]
  104. async fn migration_012_drops_reservation_and_keeps_rows_live() {
  105. let (_store, pool) = new_store_with_pool().await;
  106. // Put the column back, with a reserved row in it, then replay 012 alone.
  107. for stmt in [
  108. "ALTER TABLE live_postings ADD COLUMN reservation BIGINT",
  109. "INSERT INTO live_postings (transfer_id, idx, owner, subaccount, asset, value, reservation) VALUES ('aa', 0, 1, 0, 1, 100, NULL)",
  110. "INSERT INTO live_postings (transfer_id, idx, owner, subaccount, asset, value, reservation) VALUES ('bb', 0, 1, 0, 1, 250, 77)",
  111. "DELETE FROM _migrations WHERE name = '012_drop_reservation'",
  112. ] {
  113. sqlx::query(stmt).execute(&pool).await.unwrap();
  114. }
  115. let store = SqlStore::new(pool.clone());
  116. store.migrate().await.unwrap();
  117. let columns = sqlx::query(
  118. "SELECT column_name FROM information_schema.columns \
  119. WHERE table_schema = current_schema() AND table_name = 'live_postings' \
  120. AND column_name = 'reservation'",
  121. )
  122. .fetch_all(&pool)
  123. .await
  124. .unwrap();
  125. assert!(columns.is_empty(), "the reservation column is gone");
  126. // Both rows are still live, and the previously reserved one still sums in.
  127. let row = sqlx::query("SELECT COUNT(*) AS n, CAST(SUM(value) AS TEXT) AS s FROM live_postings")
  128. .fetch_one(&pool)
  129. .await
  130. .unwrap();
  131. assert_eq!(row.try_get::<i64, _>("n").unwrap(), 2);
  132. assert_eq!(row.try_get::<String, _>("s").unwrap(), "350");
  133. }
  134. /// The 011 migration rewrites the existing text amounts into `NUMERIC`, keeping
  135. /// their values (including negatives).
  136. #[tokio::test]
  137. async fn migration_011_converts_text_amounts() {
  138. let (_store, pool) = new_store_with_pool().await;
  139. // Roll the money columns back to their pre-011 text form, with rows in
  140. // them, then replay 011 alone.
  141. for stmt in [
  142. "ALTER TABLE postings ALTER COLUMN value TYPE TEXT USING value::text",
  143. "ALTER TABLE live_postings ALTER COLUMN value TYPE TEXT USING value::text",
  144. "ALTER TABLE balance_projection ALTER COLUMN balance TYPE TEXT USING balance::text",
  145. "INSERT INTO postings (transfer_id, idx, owner, subaccount, asset, value) VALUES ('aa', 0, 1, 0, 1, '100')",
  146. "INSERT INTO postings (transfer_id, idx, owner, subaccount, asset, value) VALUES ('bb', 0, 1, 0, 1, '-250')",
  147. "DELETE FROM _migrations WHERE name = '011_native_amounts'",
  148. ] {
  149. sqlx::query(stmt).execute(&pool).await.unwrap();
  150. }
  151. let store = SqlStore::new(pool.clone());
  152. store.migrate().await.unwrap();
  153. let rows = sqlx::query("SELECT CAST(value AS TEXT) AS v FROM postings ORDER BY transfer_id")
  154. .fetch_all(&pool)
  155. .await
  156. .unwrap();
  157. let got: Vec<String> = rows.iter().map(|r| r.try_get("v").unwrap()).collect();
  158. assert_eq!(got, vec!["100".to_string(), "-250".to_string()]);
  159. let row = sqlx::query(
  160. "SELECT data_type FROM information_schema.columns \
  161. WHERE table_schema = current_schema() AND table_name = 'postings' AND column_name = 'value'",
  162. )
  163. .fetch_one(&pool)
  164. .await
  165. .unwrap();
  166. assert_eq!(row.try_get::<String, _>("data_type").unwrap(), "numeric");
  167. }