use std::path::Path;
use axa_postgres_sqlx::{
BACKGROUND_LOCK, Background, Db, PoolConfig, begin_with, connect, dangerously_recreate,
is_unique_violation, migrate, pending, pending_background, ping, revert, run_background,
sqlx::{self, PgPool, Row, migrate::Migrator},
status, truncate,
};
async fn pool() -> PgPool {
let uri = std::env::var("AXA_TEST_DB_URL").expect("AXA_TEST_DB_URL");
connect(&PoolConfig::new(uri)).await.expect("connect")
}
async fn migrator() -> Migrator {
let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/migrations");
Migrator::new(path).await.expect("load migrations")
}
async fn table_exists(pool: &PgPool, name: &str) -> bool {
sqlx::query("SELECT to_regclass($1) IS NOT NULL AS found")
.bind(name)
.fetch_one(pool)
.await
.unwrap()
.get("found")
}
async fn count_items(pool: &PgPool) -> i64 {
sqlx::query("SELECT count(*) AS n FROM items")
.fetch_one(pool)
.await
.unwrap()
.get("n")
}
async fn insert_item(pool: &PgPool, name: &str) -> Result<i64, sqlx::Error> {
Ok(
sqlx::query("INSERT INTO items (name) VALUES ($1) RETURNING id")
.bind(name)
.fetch_one(pool)
.await?
.get("id"),
)
}
#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL and drops every table in it"]
async fn pooling_and_migrations_against_postgres() {
let pool = pool().await;
let migrator = migrator().await;
ping(&pool).await.unwrap();
dangerously_recreate(&pool, &migrator).await.unwrap();
assert!(table_exists(&pool, "items").await);
assert!(table_exists(&pool, "notes").await);
let rows = status(&pool, &migrator).await.unwrap();
assert_eq!(rows.len(), 2);
assert_eq!(rows[0].description, "create items");
assert!(rows.iter().all(|row| row.applied));
migrate(&pool, &migrator).await.unwrap();
insert_item(&pool, "one").await.unwrap();
let error = insert_item(&pool, "one").await.unwrap_err();
assert!(is_unique_violation(&error));
let error = sqlx::query("SELECT * FROM missing_table")
.execute(&pool)
.await
.unwrap_err();
assert!(!is_unique_violation(&error));
truncate(&pool, &["items"]).await.unwrap();
assert_eq!(count_items(&pool).await, 0);
assert_eq!(insert_item(&pool, "two").await.unwrap(), 1);
assert!(truncate(&pool, &["items; DROP TABLE items"]).await.is_err());
assert_eq!(count_items(&pool).await, 1);
truncate::<&str>(&pool, &[]).await.unwrap();
revert(&pool, &migrator, 1).await.unwrap();
assert!(table_exists(&pool, "items").await);
assert!(!table_exists(&pool, "notes").await);
let rows = status(&pool, &migrator).await.unwrap();
assert!(rows[0].applied);
assert!(!rows[1].applied);
revert(&pool, &migrator, 5).await.unwrap();
assert!(!table_exists(&pool, "items").await);
migrate(&pool, &migrator).await.unwrap();
assert!(table_exists(&pool, "notes").await);
insert_item(&pool, "three").await.unwrap();
dangerously_recreate(&pool, &migrator).await.unwrap();
assert_eq!(count_items(&pool).await, 0);
}
#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL and drops every table in it"]
async fn recreating_keeps_extensions() {
let pool = pool().await;
let migrator = migrator().await;
sqlx::query("CREATE EXTENSION IF NOT EXISTS citext")
.execute(&pool)
.await
.unwrap();
dangerously_recreate(&pool, &migrator).await.unwrap();
let found: i64 = sqlx::query("SELECT count(*) AS n FROM pg_extension WHERE extname = 'citext'")
.fetch_one(&pool)
.await
.unwrap()
.get("n");
assert_eq!(found, 1);
}
#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL and drops every table in it"]
async fn services_booting_together_all_migrate() {
let pool = pool().await;
let migrator = migrator().await;
dangerously_recreate(&pool, &migrator).await.unwrap();
revert(&pool, &migrator, 5).await.unwrap();
let boots: Vec<_> = (0..6)
.map(|_| {
tokio::spawn(async {
let pool = self::pool().await;
let migrator = self::migrator().await;
migrate(&pool, &migrator).await
})
})
.collect();
for boot in boots {
boot.await.unwrap().unwrap();
}
assert!(table_exists(&pool, "notes").await);
}
#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL and drops every table in it"]
async fn status_on_a_fresh_database_shows_nothing_applied() {
let pool = pool().await;
let migrator = migrator().await;
dangerously_recreate(&pool, &migrator).await.unwrap();
sqlx::query("DROP TABLE _sqlx_migrations")
.execute(&pool)
.await
.unwrap();
let rows = status(&pool, &migrator).await.unwrap();
assert!(rows.iter().all(|row| !row.applied));
assert_eq!(
pending(&pool, &migrator).await.unwrap(),
["1_create items", "2_create notes"]
);
dangerously_recreate(&pool, &migrator).await.unwrap();
assert_eq!(
pending(&pool, &migrator).await.unwrap(),
Vec::<String>::new()
);
}
async fn item_count(db: impl Into<Db<'_>>) -> Result<i64, sqlx::Error> {
let mut conn = db.into().acquire().await?;
sqlx::query_scalar("SELECT count(*) FROM items")
.fetch_one(&mut *conn)
.await
}
#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL and drops every table in it"]
async fn one_function_serves_the_pool_and_a_transaction() {
let pool = pool().await;
let migrator = migrator().await;
dangerously_recreate(&pool, &migrator).await.unwrap();
let mut tx = pool.begin().await.unwrap();
sqlx::query("INSERT INTO items (name) VALUES ('held')")
.execute(&mut *tx)
.await
.unwrap();
assert_eq!(item_count(&mut *tx).await.unwrap(), 1);
assert_eq!(item_count(&pool).await.unwrap(), 0);
tx.rollback().await.unwrap();
let spawned = tokio::spawn({
let pool = pool.clone();
async move { item_count(&pool).await }
});
assert_eq!(spawned.await.unwrap().unwrap(), 0);
}
#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL and drops every table in it"]
async fn a_setting_lasts_for_its_transaction_and_never_reaches_the_next() {
let uri = std::env::var("AXA_TEST_DB_URL").expect("AXA_TEST_DB_URL");
let mut config = PoolConfig::new(uri);
config.min_connections = 0;
config.max_connections = 1;
let pool = connect(&config).await.unwrap();
let read = "SELECT coalesce(current_setting('app.tenant', true), '') AS tenant";
let mut tx = begin_with(&pool, &[("app.tenant", "acme"), ("app.user_id", "42")])
.await
.unwrap();
let tenant: String = sqlx::query(read)
.fetch_one(&mut *tx)
.await
.unwrap()
.get("tenant");
assert_eq!(tenant, "acme");
let user: String = sqlx::query("SELECT current_setting('app.user_id') AS user_id")
.fetch_one(&mut *tx)
.await
.unwrap()
.get("user_id");
assert_eq!(user, "42");
tx.commit().await.unwrap();
let after: String = sqlx::query(read)
.fetch_one(&pool)
.await
.unwrap()
.get("tenant");
assert_eq!(after, "", "a committed setting leaked into the pool");
let mut tx = begin_with(&pool, &[("app.tenant", "globex")])
.await
.unwrap();
let _: String = sqlx::query(read)
.fetch_one(&mut *tx)
.await
.unwrap()
.get("tenant");
tx.rollback().await.unwrap();
let after: String = sqlx::query(read)
.fetch_one(&pool)
.await
.unwrap()
.get("tenant");
assert_eq!(after, "", "a rolled-back setting leaked into the pool");
let mut tx = begin_with(&pool, &[("app.tenant", "x'); RESET ALL; --")])
.await
.unwrap();
let tenant: String = sqlx::query(read)
.fetch_one(&mut *tx)
.await
.unwrap()
.get("tenant");
assert_eq!(tenant, "x'); RESET ALL; --");
tx.rollback().await.unwrap();
}
#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL as a superuser, and drops every table in it"]
async fn row_security_holds_only_for_a_role_without_bypass_on_a_forced_table() {
use axa_postgres_sqlx::row_security;
let uri = std::env::var("AXA_TEST_DB_URL").expect("AXA_TEST_DB_URL");
let mut config = PoolConfig::new(uri);
config.min_connections = 0;
config.max_connections = 1;
let pool = connect(&config).await.unwrap();
for statement in [
"DROP TABLE IF EXISTS rls_plain, rls_enabled, rls_forced",
"CREATE TABLE rls_plain (tenant_id TEXT)",
"CREATE TABLE rls_enabled (tenant_id TEXT)",
"ALTER TABLE rls_enabled ENABLE ROW LEVEL SECURITY",
"CREATE TABLE rls_forced (tenant_id TEXT)",
"ALTER TABLE rls_forced ENABLE ROW LEVEL SECURITY",
"ALTER TABLE rls_forced FORCE ROW LEVEL SECURITY",
"DROP ROLE IF EXISTS axa_rls_app",
"CREATE ROLE axa_rls_app NOLOGIN",
] {
sqlx::query(statement).execute(&pool).await.unwrap();
}
let tables = ["rls_plain", "rls_enabled", "rls_forced", "rls_missing"];
let as_superuser = row_security(&pool, &tables).await.unwrap();
assert!(as_superuser.bypasses);
assert_eq!(
as_superuser.unprotected,
["rls_plain", "rls_enabled", "rls_missing"]
);
assert!(!as_superuser.holds());
sqlx::query("SET ROLE axa_rls_app")
.execute(&pool)
.await
.unwrap();
let as_app = row_security(&pool, &["rls_forced"]).await.unwrap();
assert_eq!(as_app.role, "axa_rls_app");
assert!(!as_app.bypasses);
assert!(as_app.holds(), "{as_app:?}");
sqlx::query("RESET ROLE").execute(&pool).await.unwrap();
sqlx::query("ALTER ROLE axa_rls_app BYPASSRLS")
.execute(&pool)
.await
.unwrap();
sqlx::query("SET ROLE axa_rls_app")
.execute(&pool)
.await
.unwrap();
assert!(row_security(&pool, &["rls_forced"]).await.unwrap().bypasses);
sqlx::query("RESET ROLE").execute(&pool).await.unwrap();
sqlx::query("DROP TABLE rls_plain, rls_enabled, rls_forced")
.execute(&pool)
.await
.unwrap();
sqlx::query("DROP ROLE axa_rls_app")
.execute(&pool)
.await
.unwrap();
}
#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL and drops every table in it"]
async fn a_stale_plan_retires_the_connection_and_the_next_attempt_works() {
use axa_postgres_sqlx::{is_stale_plan, note_stale_plan};
let uri = std::env::var("AXA_TEST_DB_URL").expect("AXA_TEST_DB_URL");
let mut config = PoolConfig::new(uri);
config.min_connections = 0;
config.max_connections = 1;
let pool = connect(&config).await.unwrap();
for statement in [
"DROP TABLE IF EXISTS stale_plan",
"CREATE TABLE stale_plan (x INT)",
"INSERT INTO stale_plan VALUES (1)",
] {
sqlx::raw_sql(statement).execute(&pool).await.unwrap();
}
let select = "SELECT * FROM stale_plan";
sqlx::query(select).fetch_all(&pool).await.unwrap();
sqlx::raw_sql("ALTER TABLE stale_plan ALTER COLUMN x TYPE TEXT")
.execute(&pool)
.await
.unwrap();
let error = sqlx::query(select).fetch_all(&pool).await.unwrap_err();
assert!(is_stale_plan(&error), "{error:?}");
assert!(note_stale_plan(&error));
let rows = sqlx::query(select).fetch_all(&pool).await.unwrap();
let x: String = rows[0].get("x");
assert_eq!(x, "1");
sqlx::raw_sql("DROP TABLE stale_plan")
.execute(&pool)
.await
.unwrap();
}
#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL"]
async fn every_connection_starts_with_the_session_settings() {
let uri = std::env::var("AXA_TEST_DB_URL").expect("AXA_TEST_DB_URL");
let mut config = PoolConfig::new(uri);
config.statement_timeout_ms = 1234;
config.application_name = "axa-session-test".to_string();
config.read_only = true;
let pool = connect(&config).await.unwrap();
let show = |sql: &'static str| {
let pool = pool.clone();
async move {
let row = sqlx::query(sql).fetch_one(&pool).await.unwrap();
row.get::<String, _>(0)
}
};
assert_eq!(show("SHOW statement_timeout").await, "1234ms");
assert_eq!(show("SHOW application_name").await, "axa-session-test");
assert_eq!(show("SHOW default_transaction_read_only").await, "on");
let refused = sqlx::raw_sql("CREATE TABLE axa_read_only_refused (x INT)")
.execute(&pool)
.await
.unwrap_err();
let code = refused
.as_database_error()
.and_then(axa_postgres_sqlx::sqlx::error::DatabaseError::code);
assert_eq!(code.as_deref(), Some("25006"), "{refused:?}");
}
const NOTES_BY_ITEM: Background = Background {
name: "notes_by_item",
statements: &[
"DROP INDEX CONCURRENTLY IF EXISTS notes_by_item",
"CREATE INDEX CONCURRENTLY notes_by_item ON notes (item_id)",
],
};
const ITEMS_BY_STATE: Background = Background {
name: "items_by_state",
statements: &["CREATE INDEX CONCURRENTLY items_by_state ON items (state)"],
};
const BROKEN: Background = Background {
name: "broken",
statements: &["CREATE INDEX CONCURRENTLY broken ON no_such_table (x)"],
};
const FIXED: Background = Background {
name: "broken",
statements: &["CREATE INDEX CONCURRENTLY broken ON items (name)"],
};
const BLANK: Background = Background {
name: "",
statements: &[],
};
async fn fresh_for_background() -> PgPool {
let pool = pool().await;
dangerously_recreate(&pool, &migrator().await)
.await
.unwrap();
sqlx::query("DROP TABLE IF EXISTS axa_background_migrations")
.execute(&pool)
.await
.unwrap();
pool
}
#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL"]
async fn background_migrations_run_outside_a_transaction_once_each() {
let pool = fresh_for_background().await;
let all = [NOTES_BY_ITEM, ITEMS_BY_STATE];
assert_eq!(
pending_background(&pool, &all).await.unwrap(),
["notes_by_item", "items_by_state"]
);
let ran = run_background(&pool, &all).await.unwrap();
assert_eq!(ran.unwrap(), ["notes_by_item", "items_by_state"]);
assert!(table_exists(&pool, "notes_by_item").await);
assert!(table_exists(&pool, "items_by_state").await);
assert_eq!(
pending_background(&pool, &all).await.unwrap(),
Vec::<String>::new()
);
assert_eq!(
run_background(&pool, &all).await.unwrap().unwrap(),
Vec::<String>::new()
);
}
#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL"]
async fn a_process_finding_the_lock_held_runs_nothing() {
let pool = fresh_for_background().await;
let mut holder = pool.acquire().await.unwrap();
sqlx::query("SELECT pg_advisory_lock($1)")
.bind(BACKGROUND_LOCK)
.execute(&mut *holder)
.await
.unwrap();
assert_eq!(run_background(&pool, &[NOTES_BY_ITEM]).await.unwrap(), None);
assert!(!table_exists(&pool, "notes_by_item").await);
sqlx::query("SELECT pg_advisory_unlock($1)")
.bind(BACKGROUND_LOCK)
.execute(&mut *holder)
.await
.unwrap();
drop(holder);
assert!(
run_background(&pool, &[NOTES_BY_ITEM])
.await
.unwrap()
.is_some()
);
}
#[tokio::test]
#[ignore = "needs AXA_TEST_DB_URL"]
async fn a_failed_background_migration_is_left_to_run_again_and_frees_the_lock() {
let pool = fresh_for_background().await;
assert!(
run_background(&pool, &[NOTES_BY_ITEM, BROKEN])
.await
.is_err()
);
assert_eq!(
pending_background(&pool, &[NOTES_BY_ITEM, BROKEN])
.await
.unwrap(),
["broken"]
);
let ran = run_background(&pool, &[NOTES_BY_ITEM, FIXED])
.await
.unwrap();
assert_eq!(
ran.unwrap(),
["broken"],
"the lock was freed, and only it ran"
);
}
#[tokio::test]
async fn a_background_migration_named_twice_or_badly_is_refused() {
let pool = sqlx::postgres::PgPoolOptions::new()
.connect_lazy("postgres://axa:axa@127.0.0.1:1/axa")
.unwrap();
let twice = run_background(&pool, &[NOTES_BY_ITEM, NOTES_BY_ITEM]).await;
assert!(
matches!(twice, Err(sqlx::Error::Configuration(_))),
"{twice:?}"
);
let blank = run_background(&pool, &[BLANK]).await;
assert!(
matches!(blank, Err(sqlx::Error::Configuration(_))),
"{blank:?}"
);
}