| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219 |
- #![allow(missing_docs)]
- #![cfg(feature = "test-postgres")]
- //! PostgreSQL conformance run.
- //!
- //! The same `store_tests!` suite the SQLite backend passes, driven against a
- //! real PostgreSQL instance so the Postgres-only code paths (the `FOR UPDATE`
- //! row locks behind `lock_clause`, the `ON CONFLICT` upserts) are actually
- //! exercised. Point `DATABASE_URL` at a Postgres database to run it; the CI
- //! `Test (PostgreSQL)` job supplies one.
- //!
- //! Unlike `sqlite::memory:`, where every pool is its own fresh database, all
- //! tests here share one Postgres database and the conformance tests reuse fixed
- //! ids. Each store therefore gets its own uniquely-named schema, and the pool is
- //! pinned to a single connection so the session `search_path` set below persists
- //! for the store's whole lifetime.
- use std::sync::atomic::{AtomicU64, Ordering};
- use kuatia_storage::store::PostingStore;
- use kuatia_storage::store_tests::seed_live;
- use kuatia_storage_sql::SqlStore;
- use kuatia_types::*;
- use sqlx::{Any, Pool, Row};
- static SCHEMA_SEQ: AtomicU64 = AtomicU64::new(0);
- async fn new_store() -> SqlStore {
- new_store_with_pool().await.0
- }
- async fn new_store_with_pool() -> (SqlStore, Pool<Any>) {
- kuatia_storage_sql::install_drivers().expect("install drivers");
- let url = std::env::var("DATABASE_URL")
- .expect("DATABASE_URL must point at a PostgreSQL instance for this suite");
- // One connection per store so the session-level `search_path` set below
- // survives across every query the store issues.
- let pool: Pool<Any> = sqlx::any::AnyPoolOptions::new()
- .max_connections(1)
- .connect(&url)
- .await
- .unwrap();
- // Isolate each store in its own schema: the conformance tests reuse fixed
- // ids, so a shared schema would collide across tests.
- let n = SCHEMA_SEQ.fetch_add(1, Ordering::Relaxed);
- let schema = format!("conformance_{n}");
- for stmt in [
- format!("DROP SCHEMA IF EXISTS {schema} CASCADE"),
- format!("CREATE SCHEMA {schema}"),
- format!("SET search_path TO {schema}"),
- ] {
- sqlx::query(&stmt).execute(&pool).await.unwrap();
- }
- let store = SqlStore::new(pool.clone());
- store.migrate().await.unwrap();
- (store, pool)
- }
- kuatia_storage::store_tests!(new_store);
- /// Amounts are stored as native `NUMERIC`, not text, and round-trip through the
- /// store. The type assertion is the point: under `sqlx::Any` an uncast
- /// `NUMERIC` fails the whole row, so this also proves every money `SELECT`
- /// goes through `Dialect::money_read` (ADR-0024).
- #[tokio::test]
- async fn amount_columns_are_numeric() {
- let (store, pool) = new_store_with_pool().await;
- let posting = Posting::new(
- PostingId {
- transfer: TransferId([0x3f; 32]),
- index: 0,
- },
- AccountId::new(1),
- AssetId::new(1),
- Cent::from(-4321),
- );
- seed_live(&store, 0x3f, std::slice::from_ref(&posting)).await;
- let got = store.get_postings(&[posting.id]).await.unwrap();
- assert_eq!(got[0].value, Cent::from(-4321));
- assert_eq!(
- store
- .live_balance(&AccountId::new(1), &AssetId::new(1))
- .await
- .unwrap(),
- Cent::from(-4321)
- );
- for (table, column) in [
- ("postings", "value"),
- ("live_postings", "value"),
- ("balance_projection", "balance"),
- ] {
- let row = sqlx::query(
- "SELECT data_type FROM information_schema.columns \
- WHERE table_schema = current_schema() AND table_name = $1 AND column_name = $2",
- )
- .bind(table)
- .bind(column)
- .fetch_one(&pool)
- .await
- .unwrap();
- assert_eq!(
- row.try_get::<String, _>("data_type").unwrap(),
- "numeric",
- "{table}.{column}"
- );
- }
- }
- /// The 013 migration adds the value-date column, and an existing row gets NULL:
- /// an entry booked before the column existed was valued the day it was booked.
- #[tokio::test]
- async fn migration_013_adds_value_date_as_null_for_existing_rows() {
- let (_store, pool) = new_store_with_pool().await;
- for stmt in [
- "ALTER TABLE transfers DROP COLUMN value_date",
- "INSERT INTO transfers (id, transfer, receipt, created_at, book) VALUES ('aa', '{}', '{}', 5, 0)",
- "DELETE FROM _migrations WHERE name = '013_value_date'",
- ] {
- sqlx::query(stmt).execute(&pool).await.unwrap();
- }
- let store = SqlStore::new(pool.clone());
- store.migrate().await.unwrap();
- let row = sqlx::query("SELECT value_date FROM transfers WHERE id = 'aa'")
- .fetch_one(&pool)
- .await
- .unwrap();
- assert!(
- row.try_get::<Option<i64>, _>("value_date")
- .unwrap()
- .is_none(),
- "an entry booked before the column existed carries no value date"
- );
- }
- /// The 012 migration drops the reservation column and leaves every live row
- /// live, including one that still carried a token: it was never consumed, so it
- /// must stay spendable and keep counting toward the balance.
- #[tokio::test]
- async fn migration_012_drops_reservation_and_keeps_rows_live() {
- let (_store, pool) = new_store_with_pool().await;
- // Put the column back, with a reserved row in it, then replay 012 alone.
- for stmt in [
- "ALTER TABLE live_postings ADD COLUMN reservation BIGINT",
- "INSERT INTO live_postings (transfer_id, idx, owner, subaccount, asset, value, reservation) VALUES ('aa', 0, 1, 0, 1, 100, NULL)",
- "INSERT INTO live_postings (transfer_id, idx, owner, subaccount, asset, value, reservation) VALUES ('bb', 0, 1, 0, 1, 250, 77)",
- "DELETE FROM _migrations WHERE name = '012_drop_reservation'",
- ] {
- sqlx::query(stmt).execute(&pool).await.unwrap();
- }
- let store = SqlStore::new(pool.clone());
- store.migrate().await.unwrap();
- let columns = sqlx::query(
- "SELECT column_name FROM information_schema.columns \
- WHERE table_schema = current_schema() AND table_name = 'live_postings' \
- AND column_name = 'reservation'",
- )
- .fetch_all(&pool)
- .await
- .unwrap();
- assert!(columns.is_empty(), "the reservation column is gone");
- // Both rows are still live, and the previously reserved one still sums in.
- let row = sqlx::query("SELECT COUNT(*) AS n, CAST(SUM(value) AS TEXT) AS s FROM live_postings")
- .fetch_one(&pool)
- .await
- .unwrap();
- assert_eq!(row.try_get::<i64, _>("n").unwrap(), 2);
- assert_eq!(row.try_get::<String, _>("s").unwrap(), "350");
- }
- /// The 011 migration rewrites the existing text amounts into `NUMERIC`, keeping
- /// their values (including negatives).
- #[tokio::test]
- async fn migration_011_converts_text_amounts() {
- let (_store, pool) = new_store_with_pool().await;
- // Roll the money columns back to their pre-011 text form, with rows in
- // them, then replay 011 alone.
- for stmt in [
- "ALTER TABLE postings ALTER COLUMN value TYPE TEXT USING value::text",
- "ALTER TABLE live_postings ALTER COLUMN value TYPE TEXT USING value::text",
- "ALTER TABLE balance_projection ALTER COLUMN balance TYPE TEXT USING balance::text",
- "INSERT INTO postings (transfer_id, idx, owner, subaccount, asset, value) VALUES ('aa', 0, 1, 0, 1, '100')",
- "INSERT INTO postings (transfer_id, idx, owner, subaccount, asset, value) VALUES ('bb', 0, 1, 0, 1, '-250')",
- "DELETE FROM _migrations WHERE name = '011_native_amounts'",
- ] {
- sqlx::query(stmt).execute(&pool).await.unwrap();
- }
- let store = SqlStore::new(pool.clone());
- store.migrate().await.unwrap();
- let rows = sqlx::query("SELECT CAST(value AS TEXT) AS v FROM postings ORDER BY transfer_id")
- .fetch_all(&pool)
- .await
- .unwrap();
- let got: Vec<String> = rows.iter().map(|r| r.try_get("v").unwrap()).collect();
- assert_eq!(got, vec!["100".to_string(), "-250".to_string()]);
- let row = sqlx::query(
- "SELECT data_type FROM information_schema.columns \
- WHERE table_schema = current_schema() AND table_name = 'postings' AND column_name = 'value'",
- )
- .fetch_one(&pool)
- .await
- .unwrap();
- assert_eq!(row.try_get::<String, _>("data_type").unwrap(), "numeric");
- }
|