postgres.rs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  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 run for real: the
  7. //! `FOR UPDATE` row locks behind `lock_clause`, and the `ON CONFLICT` upserts.
  8. //! Point `DATABASE_URL` at a Postgres database to run it, and 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
  13. //! fixed ids. So each store gets its own uniquely-named schema. The pool is
  14. //! also pinned to a single connection. That is what makes the session
  15. //! `search_path` set below last for the whole life of the store.
  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` and not text, and they round-trip
  65. /// through the store. The type assertion is the point. Under `sqlx::Any` an
  66. /// uncast `NUMERIC` fails the whole row, so this also proves that every money
  67. /// `SELECT` 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 a row that is already
  112. /// there gets NULL. An entry booked before the column existed was valued on the
  113. /// day it was booked.
  114. #[tokio::test]
  115. async fn migration_013_adds_value_date_as_null_for_existing_rows() {
  116. let (_store, pool) = new_store_with_pool().await;
  117. for stmt in [
  118. "ALTER TABLE transfers DROP COLUMN value_date",
  119. "INSERT INTO transfers (id, transfer, receipt, created_at, book) VALUES ('aa', '{}', '{}', 5, 0)",
  120. "DELETE FROM _migrations WHERE name = '013_value_date'",
  121. ] {
  122. sqlx::query(stmt).execute(&pool).await.unwrap();
  123. }
  124. let store = SqlStore::new(pool.clone());
  125. store.migrate().await.unwrap();
  126. let row = sqlx::query("SELECT value_date FROM transfers WHERE id = 'aa'")
  127. .fetch_one(&pool)
  128. .await
  129. .unwrap();
  130. assert!(
  131. row.try_get::<Option<i64>, _>("value_date")
  132. .unwrap()
  133. .is_none(),
  134. "an entry booked before the column existed carries no value date"
  135. );
  136. }
  137. /// The 012 migration drops the reservation column and leaves every live row
  138. /// live. That covers a row that still carried a token. It was never consumed,
  139. /// so it must stay spendable and it must still count toward the balance.
  140. #[tokio::test]
  141. async fn migration_012_drops_reservation_and_keeps_rows_live() {
  142. let (_store, pool) = new_store_with_pool().await;
  143. // Put the column back, with a reserved row in it, then replay 012 alone.
  144. for stmt in [
  145. "ALTER TABLE live_postings ADD COLUMN reservation BIGINT",
  146. "INSERT INTO live_postings (transfer_id, idx, owner, subaccount, asset, value, reservation) VALUES ('aa', 0, 1, 0, 1, 100, NULL)",
  147. "INSERT INTO live_postings (transfer_id, idx, owner, subaccount, asset, value, reservation) VALUES ('bb', 0, 1, 0, 1, 250, 77)",
  148. "DELETE FROM _migrations WHERE name = '012_drop_reservation'",
  149. ] {
  150. sqlx::query(stmt).execute(&pool).await.unwrap();
  151. }
  152. let store = SqlStore::new(pool.clone());
  153. store.migrate().await.unwrap();
  154. let columns = sqlx::query(
  155. "SELECT column_name FROM information_schema.columns \
  156. WHERE table_schema = current_schema() AND table_name = 'live_postings' \
  157. AND column_name = 'reservation'",
  158. )
  159. .fetch_all(&pool)
  160. .await
  161. .unwrap();
  162. assert!(columns.is_empty(), "the reservation column is gone");
  163. // Both rows are still live, and the previously reserved one still sums in.
  164. let row = sqlx::query("SELECT COUNT(*) AS n, CAST(SUM(value) AS TEXT) AS s FROM live_postings")
  165. .fetch_one(&pool)
  166. .await
  167. .unwrap();
  168. assert_eq!(row.try_get::<i64, _>("n").unwrap(), 2);
  169. assert_eq!(row.try_get::<String, _>("s").unwrap(), "350");
  170. }
  171. /// The 011 migration rewrites the text amounts already stored into `NUMERIC`,
  172. /// and it keeps their values, a negative one too.
  173. #[tokio::test]
  174. async fn migration_011_converts_text_amounts() {
  175. let (_store, pool) = new_store_with_pool().await;
  176. // Roll the money columns back to their pre-011 text form, with rows in
  177. // them, then replay 011 alone.
  178. for stmt in [
  179. "ALTER TABLE postings ALTER COLUMN value TYPE TEXT USING value::text",
  180. "ALTER TABLE live_postings ALTER COLUMN value TYPE TEXT USING value::text",
  181. "ALTER TABLE balance_projection ALTER COLUMN balance TYPE TEXT USING balance::text",
  182. "INSERT INTO postings (transfer_id, idx, owner, subaccount, asset, value) VALUES ('aa', 0, 1, 0, 1, '100')",
  183. "INSERT INTO postings (transfer_id, idx, owner, subaccount, asset, value) VALUES ('bb', 0, 1, 0, 1, '-250')",
  184. "DELETE FROM _migrations WHERE name = '011_native_amounts'",
  185. ] {
  186. sqlx::query(stmt).execute(&pool).await.unwrap();
  187. }
  188. let store = SqlStore::new(pool.clone());
  189. store.migrate().await.unwrap();
  190. let rows = sqlx::query("SELECT CAST(value AS TEXT) AS v FROM postings ORDER BY transfer_id")
  191. .fetch_all(&pool)
  192. .await
  193. .unwrap();
  194. let got: Vec<String> = rows.iter().map(|r| r.try_get("v").unwrap()).collect();
  195. assert_eq!(got, vec!["100".to_string(), "-250".to_string()]);
  196. let row = sqlx::query(
  197. "SELECT data_type FROM information_schema.columns \
  198. WHERE table_schema = current_schema() AND table_name = 'postings' AND column_name = 'value'",
  199. )
  200. .fetch_one(&pool)
  201. .await
  202. .unwrap();
  203. assert_eq!(row.try_get::<String, _>("data_type").unwrap(), "numeric");
  204. }