postgres.rs 5.4 KB

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