footing 0.1.21

Feature-gated foundations for Rust backend services
Documentation
//! PostgreSQL integration tests. CI supplies an isolated disposable database.

#![cfg(feature = "postgres-admin")]

use std::{path::PathBuf, time::Duration};

use footing::db::postgres::admin::{PostgresResetError, PostgresResetSettings, reset_database};
use footing::db::postgres::{
    PostgresMigrationRunError, PostgresPoolSettings, advisory_lock_key, connect_pool,
    database_name, ensure_database_exists, run_migrations_with_timeouts,
    schema_maintenance_advisory_lock_key,
};
use sqlx::migrate::{MigrateDatabase, Migrator};

const POSTGRES_TEST_DATABASE: &str = "footing_test";
const REQUIRE_POSTGRES_TESTS_ENV: &str = "FOOTING_REQUIRE_POSTGRES_TESTS";
const ALLOW_DESTRUCTIVE_POSTGRES_TESTS_ENV: &str = "FOOTING_ALLOW_DESTRUCTIVE_POSTGRES_TESTS";

fn test_database_url() -> Option<String> {
    let required = std::env::var(REQUIRE_POSTGRES_TESTS_ENV).as_deref() == Ok("1");
    let database_url = match std::env::var("FOOTING_TEST_POSTGRES_URL") {
        Ok(database_url) => database_url,
        Err(error) => {
            assert!(
                !required,
                "{REQUIRE_POSTGRES_TESTS_ENV}=1 requires FOOTING_TEST_POSTGRES_URL: {error}"
            );
            return None;
        }
    };
    assert_eq!(
        std::env::var(ALLOW_DESTRUCTIVE_POSTGRES_TESTS_ENV).as_deref(),
        Ok("1"),
        "PostgreSQL integration tests can reset the public schema; set \
         {ALLOW_DESTRUCTIVE_POSTGRES_TESTS_ENV}=1 only for the disposable test database"
    );
    assert_eq!(
        database_name(&database_url).as_deref(),
        Some(POSTGRES_TEST_DATABASE),
        "destructive PostgreSQL integration tests must target the fixed disposable database \
         {POSTGRES_TEST_DATABASE:?}"
    );
    Some(database_url)
}

fn migration_directory() -> PathBuf {
    std::env::temp_dir().join(format!(
        "footing-postgres-migrations-{}-{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .expect("system clock must be after the Unix epoch")
            .as_nanos()
    ))
}

#[tokio::test]
async fn database_creation_quotes_identifiers_and_tolerates_competing_creators() {
    let Some(database_url) = test_database_url() else {
        return;
    };
    let name = format!(
        "footing_ensure_{}_{}\"quoted",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos()
    );
    let mut url = url::Url::parse(&database_url).unwrap();
    url.set_path(&name);
    url.query_pairs_mut().append_pair("dbname", &name);
    let (first, second) = tokio::join!(
        ensure_database_exists(url.as_str(), Duration::from_secs(30)),
        ensure_database_exists(url.as_str(), Duration::from_secs(30))
    );
    first.expect("first creator should succeed");
    second.expect("competing creator should succeed");
    ensure_database_exists(url.as_str(), Duration::from_secs(30))
        .await
        .expect("an existing database must remain usable");

    let pool = connect_pool(
        url.as_str(),
        PostgresPoolSettings::default().build().unwrap(),
    )
    .await
    .unwrap();
    let actual: String = sqlx::query_scalar("SELECT current_database()")
        .fetch_one(&pool)
        .await
        .unwrap();
    pool.close().await;
    // Only remove the uniquely named database created by this test.
    sqlx::Postgres::drop_database(url.as_str()).await.unwrap();
    assert_eq!(actual, name);

    url.set_path("/postgres");
    url.query_pairs_mut().append_pair("dbname", "postgres");
    ensure_database_exists(url.as_str(), Duration::from_secs(30))
        .await
        .expect("the postgres database must use template1 for maintenance");
}

#[tokio::test]
async fn migration_lock_and_execution_respect_deadlines() {
    let Some(database_url) = test_database_url() else {
        return;
    };
    let pool = connect_pool(
        &database_url,
        PostgresPoolSettings::default()
            .build()
            .expect("default pool settings are valid"),
    )
    .await
    .expect("integration database must be available");
    let database_name = database_name(&database_url).expect("test URL must name a database");
    let coordinator_key = advisory_lock_key("footing.test", "postgres-integration-suite");
    let lock_key = schema_maintenance_advisory_lock_key(&database_name);
    let mut holder = pool.acquire().await.expect("lock holder must connect");
    sqlx::query("SELECT pg_advisory_lock($1)")
        .bind(coordinator_key)
        .execute(&mut *holder)
        .await
        .expect("test coordinator lock must be acquired");
    sqlx::query("SELECT pg_advisory_lock($1)")
        .bind(lock_key)
        .execute(&mut *holder)
        .await
        .expect("test lock must be acquired");

    let directory = migration_directory();
    std::fs::create_dir_all(&directory).expect("migration directory must be created");
    let migrator = Migrator::new(directory.clone())
        .await
        .expect("empty migration directory is valid");
    let error = run_migrations_with_timeouts(
        &pool,
        &migrator,
        None,
        Duration::from_millis(100),
        Duration::from_secs(2),
    )
    .await
    .expect_err("a held advisory lock must hit the configured deadline");

    assert!(matches!(
        error,
        PostgresMigrationRunError::LockTimeout { .. }
    ));
    let unlocked: bool = sqlx::query_scalar("SELECT pg_advisory_unlock($1)")
        .bind(lock_key)
        .fetch_one(&mut *holder)
        .await
        .expect("test lock must be released");
    assert!(unlocked);

    std::fs::write(
        directory.join("20260831000000_slow.sql"),
        "SELECT pg_sleep(1);",
    )
    .expect("slow migration must be written");
    let slow_migrator = Migrator::new(directory.clone())
        .await
        .expect("slow migration directory must be valid");
    let error = run_migrations_with_timeouts(
        &pool,
        &slow_migrator,
        None,
        Duration::from_secs(2),
        Duration::from_millis(100),
    )
    .await
    .expect_err("a slow migration must hit the execution deadline");
    assert!(matches!(
        error,
        PostgresMigrationRunError::MigrationTimeout { .. }
    ));

    let coordinator_unlocked: bool = sqlx::query_scalar("SELECT pg_advisory_unlock($1)")
        .bind(coordinator_key)
        .fetch_one(&mut *holder)
        .await
        .expect("test coordinator lock must be released");
    assert!(coordinator_unlocked);
    std::fs::remove_dir_all(&directory).expect("migration directory must be removed");
}

#[tokio::test]
async fn reset_is_exclusive_and_recreates_schema_atomically() {
    let Some(database_url) = test_database_url() else {
        return;
    };
    let pool = connect_pool(
        &database_url,
        PostgresPoolSettings::default()
            .build()
            .expect("default pool settings are valid"),
    )
    .await
    .expect("integration database must be available");
    let name = database_name(&database_url).expect("test URL must name a database");
    let coordinator_key = advisory_lock_key("footing.test", "postgres-integration-suite");
    let reset_key = schema_maintenance_advisory_lock_key(&name);
    let mut holder = pool.acquire().await.expect("lock holder must connect");
    sqlx::query("SELECT pg_advisory_lock($1)")
        .bind(coordinator_key)
        .execute(&mut *holder)
        .await
        .expect("test coordinator lock must be acquired");
    sqlx::query("SELECT pg_advisory_lock($1)")
        .bind(reset_key)
        .execute(&mut *holder)
        .await
        .expect("test reset lock must be acquired");

    let blocked = PostgresResetSettings::new(&database_url)
        .with_reset_lock_timeout(Duration::from_millis(100))
        .build()
        .expect("reset settings must be valid");
    let error = reset_database(blocked, None)
        .await
        .expect_err("concurrent reset must not pass the exclusive lock");
    assert!(matches!(error, PostgresResetError::ResetLockTimeout { .. }));

    let unlocked: bool = sqlx::query_scalar("SELECT pg_advisory_unlock($1)")
        .bind(reset_key)
        .fetch_one(&mut *holder)
        .await
        .expect("test reset lock must be released");
    assert!(unlocked);

    sqlx::query("CREATE TABLE IF NOT EXISTS public.footing_reset_marker (id integer)")
        .execute(&pool)
        .await
        .expect("marker table must be created");
    let mut blocker = pool.acquire().await.expect("DDL blocker must connect");
    sqlx::query("BEGIN")
        .execute(&mut *blocker)
        .await
        .expect("DDL blocker transaction must begin");
    sqlx::query("LOCK TABLE public.footing_reset_marker IN ACCESS SHARE MODE")
        .execute(&mut *blocker)
        .await
        .expect("DDL blocker must hold an incompatible schema-reset lock");
    let timed_reset = PostgresResetSettings::new(&database_url)
        .with_reset_lock_timeout(Duration::from_secs(2))
        .with_reset_schema_timeout(Duration::from_millis(100))
        .build()
        .expect("timed reset settings must be valid");
    let error = reset_database(timed_reset, None)
        .await
        .expect_err("blocked schema reset must hit its execution deadline");
    assert!(matches!(
        error,
        PostgresResetError::ResetSchemaTimeout { .. }
    ));
    sqlx::query("ROLLBACK")
        .execute(&mut *blocker)
        .await
        .expect("DDL blocker transaction must roll back");
    drop(blocker);

    let marker_after_timeout: Option<String> =
        sqlx::query_scalar("SELECT to_regclass('public.footing_reset_marker')::text")
            .fetch_one(&pool)
            .await
            .expect("marker lookup after timed-out reset must succeed");
    assert_eq!(
        marker_after_timeout.as_deref(),
        Some("footing_reset_marker"),
        "timed-out transactional reset must leave the original schema intact"
    );

    let reset = PostgresResetSettings::new(&database_url)
        .with_reset_lock_timeout(Duration::from_secs(2))
        .build()
        .expect("reset settings must be valid");
    reset_database(reset, None)
        .await
        .expect("isolated test database must reset successfully");

    let marker: Option<String> =
        sqlx::query_scalar("SELECT to_regclass('public.footing_reset_marker')::text")
            .fetch_one(&pool)
            .await
            .expect("marker lookup must succeed");
    assert!(marker.is_none());
    let public_schema: bool =
        sqlx::query_scalar("SELECT EXISTS (SELECT 1 FROM pg_namespace WHERE nspname = 'public')")
            .fetch_one(&pool)
            .await
            .expect("public schema lookup must succeed");
    assert!(public_schema);

    let coordinator_unlocked: bool = sqlx::query_scalar("SELECT pg_advisory_unlock($1)")
        .bind(coordinator_key)
        .fetch_one(&mut *holder)
        .await
        .expect("test coordinator lock must be released");
    assert!(coordinator_unlocked);
}