postgres.rs 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  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 013 migration adds the value-date column, and an existing row gets NULL:
  101. /// an entry booked before the column existed was valued the day it was booked.
  102. #[tokio::test]
  103. async fn migration_013_adds_value_date_as_null_for_existing_rows() {
  104. let (_store, pool) = new_store_with_pool().await;
  105. for stmt in [
  106. "ALTER TABLE transfers DROP COLUMN value_date",
  107. "INSERT INTO transfers (id, transfer, receipt, created_at, book) VALUES ('aa', '{}', '{}', 5, 0)",
  108. "DELETE FROM _migrations WHERE name = '013_value_date'",
  109. ] {
  110. sqlx::query(stmt).execute(&pool).await.unwrap();
  111. }
  112. let store = SqlStore::new(pool.clone());
  113. store.migrate().await.unwrap();
  114. let row = sqlx::query("SELECT value_date FROM transfers WHERE id = 'aa'")
  115. .fetch_one(&pool)
  116. .await
  117. .unwrap();
  118. assert!(
  119. row.try_get::<Option<i64>, _>("value_date")
  120. .unwrap()
  121. .is_none(),
  122. "an entry booked before the column existed carries no value date"
  123. );
  124. }
  125. /// The 012 migration drops the reservation column and leaves every live row
  126. /// live, including one that still carried a token: it was never consumed, so it
  127. /// must stay spendable and keep counting toward the balance.
  128. #[tokio::test]
  129. async fn migration_012_drops_reservation_and_keeps_rows_live() {
  130. let (_store, pool) = new_store_with_pool().await;
  131. // Put the column back, with a reserved row in it, then replay 012 alone.
  132. for stmt in [
  133. "ALTER TABLE live_postings ADD COLUMN reservation BIGINT",
  134. "INSERT INTO live_postings (transfer_id, idx, owner, subaccount, asset, value, reservation) VALUES ('aa', 0, 1, 0, 1, 100, NULL)",
  135. "INSERT INTO live_postings (transfer_id, idx, owner, subaccount, asset, value, reservation) VALUES ('bb', 0, 1, 0, 1, 250, 77)",
  136. "DELETE FROM _migrations WHERE name = '012_drop_reservation'",
  137. ] {
  138. sqlx::query(stmt).execute(&pool).await.unwrap();
  139. }
  140. let store = SqlStore::new(pool.clone());
  141. store.migrate().await.unwrap();
  142. let columns = sqlx::query(
  143. "SELECT column_name FROM information_schema.columns \
  144. WHERE table_schema = current_schema() AND table_name = 'live_postings' \
  145. AND column_name = 'reservation'",
  146. )
  147. .fetch_all(&pool)
  148. .await
  149. .unwrap();
  150. assert!(columns.is_empty(), "the reservation column is gone");
  151. // Both rows are still live, and the previously reserved one still sums in.
  152. let row = sqlx::query("SELECT COUNT(*) AS n, CAST(SUM(value) AS TEXT) AS s FROM live_postings")
  153. .fetch_one(&pool)
  154. .await
  155. .unwrap();
  156. assert_eq!(row.try_get::<i64, _>("n").unwrap(), 2);
  157. assert_eq!(row.try_get::<String, _>("s").unwrap(), "350");
  158. }
  159. /// The 011 migration rewrites the existing text amounts into `NUMERIC`, keeping
  160. /// their values (including negatives).
  161. #[tokio::test]
  162. async fn migration_011_converts_text_amounts() {
  163. let (_store, pool) = new_store_with_pool().await;
  164. // Roll the money columns back to their pre-011 text form, with rows in
  165. // them, then replay 011 alone.
  166. for stmt in [
  167. "ALTER TABLE postings ALTER COLUMN value TYPE TEXT USING value::text",
  168. "ALTER TABLE live_postings ALTER COLUMN value TYPE TEXT USING value::text",
  169. "ALTER TABLE balance_projection ALTER COLUMN balance TYPE TEXT USING balance::text",
  170. "INSERT INTO postings (transfer_id, idx, owner, subaccount, asset, value) VALUES ('aa', 0, 1, 0, 1, '100')",
  171. "INSERT INTO postings (transfer_id, idx, owner, subaccount, asset, value) VALUES ('bb', 0, 1, 0, 1, '-250')",
  172. "DELETE FROM _migrations WHERE name = '011_native_amounts'",
  173. ] {
  174. sqlx::query(stmt).execute(&pool).await.unwrap();
  175. }
  176. let store = SqlStore::new(pool.clone());
  177. store.migrate().await.unwrap();
  178. let rows = sqlx::query("SELECT CAST(value AS TEXT) AS v FROM postings ORDER BY transfer_id")
  179. .fetch_all(&pool)
  180. .await
  181. .unwrap();
  182. let got: Vec<String> = rows.iter().map(|r| r.try_get("v").unwrap()).collect();
  183. assert_eq!(got, vec!["100".to_string(), "-250".to_string()]);
  184. let row = sqlx::query(
  185. "SELECT data_type FROM information_schema.columns \
  186. WHERE table_schema = current_schema() AND table_name = 'postings' AND column_name = 'value'",
  187. )
  188. .fetch_one(&pool)
  189. .await
  190. .unwrap();
  191. assert_eq!(row.try_get::<String, _>("data_type").unwrap(), "numeric");
  192. }