footing 0.1.6

Feature-gated foundations for Rust backend services
Documentation
use crate::{
    db::MigrationFailureKind,
    result::{ClassifyError, DiagnosticKind},
};

use super::{
    SQLITE_HEALTH_ERROR, SqliteBootstrapError, SqliteBootstrapSettings, SqliteConnectionSettings,
    SqliteDiagnosticKind, SqliteHealth, SqliteHealthStatus, SqliteJournalMode, SqliteOperation,
    SqlitePoolError, SqlitePoolSettings, SqliteSynchronousMode, begin_transaction,
    bootstrap_database, check_pool_health, commit_transaction, connect_options, connect_pool,
    connect_pool_with_options, diagnose_migration_error, diagnose_pool_error, ping_pool,
    rollback_transaction,
};

struct TempDatabase(std::path::PathBuf);

impl TempDatabase {
    fn new() -> Self {
        static NEXT_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
        let id = NEXT_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        Self(std::env::temp_dir().join(format!("footing-sqlite-{}-{id}.db", std::process::id())))
    }

    fn url(&self) -> String {
        format!("sqlite://{}", self.0.display())
    }
}

impl Drop for TempDatabase {
    fn drop(&mut self) {
        let _ = std::fs::remove_file(&self.0);
    }
}

#[test]
fn validates_pool_settings_with_stable_paths() {
    let error = SqlitePoolSettings::default()
        .with_max_connections(0)
        .with_acquire_timeout(std::time::Duration::ZERO)
        .build()
        .expect_err("invalid pool settings must be rejected");

    assert_eq!(error.issues()[0].path(), "sqlite.pool.max_connections");
    assert_eq!(error.issues()[1].path(), "sqlite.pool.acquire_timeout");

    let error = SqlitePoolSettings::default()
        .with_max_connections(2)
        .with_min_connections(3)
        .build()
        .expect_err("minimum connections above maximum must be rejected");
    assert_eq!(error.issues()[0].path(), "sqlite.pool.min_connections");
}

#[test]
fn exposes_validated_pool_values() {
    let config = SqlitePoolSettings::default()
        .with_max_connections(3)
        .with_min_connections(1)
        .with_test_before_acquire(false)
        .build()
        .expect("pool settings should be valid");

    assert_eq!(config.max_connections(), 3);
    assert_eq!(config.min_connections(), 1);
    assert!(!config.test_before_acquire());
}

#[test]
fn validates_connection_settings_before_opening_a_database() {
    let invalid_url = SqliteBootstrapSettings::new("postgres://localhost/app")
        .build()
        .expect_err("a non-SQLite URL must be rejected");
    assert_eq!(
        invalid_url.issues()[0].path(),
        "sqlite.connection.database_url"
    );

    let incompatible = SqliteBootstrapSettings::from_connection(
        SqliteConnectionSettings::new("sqlite://app.db")
            .with_read_only(true)
            .with_create_if_missing(true),
    )
    .build()
    .expect_err("read-only creation must be rejected");
    assert_eq!(
        incompatible.issues()[0].path(),
        "sqlite.connection.create_if_missing"
    );

    let ambiguous = SqliteBootstrapSettings::new("sqlite://app.db?mode=ro")
        .build()
        .expect_err("URL parameters must not compete with explicit settings");
    assert_eq!(
        ambiguous.issues()[0].path(),
        "sqlite.connection.database_url"
    );

    let read_only_journal = SqliteBootstrapSettings::from_connection(
        SqliteConnectionSettings::new("sqlite://app.db")
            .with_read_only(true)
            .with_journal_mode(Some(SqliteJournalMode::Wal)),
    )
    .build()
    .expect_err("read-only settings must not alter journal mode");
    assert_eq!(
        read_only_journal.issues()[0].path(),
        "sqlite.connection.journal_mode"
    );

    let read_only_migration = SqliteBootstrapSettings::from_connection(
        SqliteConnectionSettings::new("sqlite://app.db").with_read_only(true),
    )
    .with_migrate_on_startup(true)
    .build()
    .expect_err("read-only settings must not run migrations");
    assert_eq!(
        read_only_migration.issues()[0].path(),
        "sqlite.migrate_on_startup"
    );
}

#[test]
fn settings_build_complete_runtime_configuration() {
    let connection = SqliteConnectionSettings::new("sqlite://app.db")
        .with_create_if_missing(true)
        .with_foreign_keys(false)
        .with_busy_timeout(std::time::Duration::from_secs(2))
        .with_journal_mode(Some(SqliteJournalMode::Wal))
        .with_synchronous(Some(SqliteSynchronousMode::Normal))
        .with_statement_cache_capacity(64);
    let config = SqliteBootstrapSettings::from_connection(connection)
        .with_pool(SqlitePoolSettings::default().with_max_connections(3))
        .build()
        .expect("settings should be valid");

    let connection = config.connection_config();
    assert_eq!(connection.database_url(), "sqlite://app.db");
    assert_eq!(config.pool_config().max_connections(), 3);
    assert!(connection.create_if_missing());
    assert!(!connection.read_only());
    assert!(!connection.foreign_keys());
    assert_eq!(connection.busy_timeout(), std::time::Duration::from_secs(2));
    assert_eq!(connection.journal_mode(), Some(SqliteJournalMode::Wal));
    assert_eq!(
        connection.synchronous(),
        Some(SqliteSynchronousMode::Normal)
    );
    assert_eq!(connection.statement_cache_capacity(), 64);
    assert!(!config.migrate_on_startup());
}

#[test]
fn sqlite_debug_output_redacts_database_locations() {
    let settings = SqliteBootstrapSettings::new("sqlite:///private/customer/app.db");
    let config = settings.clone().build().expect("settings should be valid");
    let output = format!("{settings:?} {config:?}");

    assert!(output.contains("[REDACTED]"));
    assert!(!output.contains("/private/customer/app.db"));
}

#[test]
fn settings_deserialize_sqlite_specific_options() {
    let settings: SqliteBootstrapSettings = serde_json::from_value(serde_json::json!({
        "connection": {
            "database_url": "sqlite://app.db",
            "journal_mode": "wal",
            "synchronous": "normal",
            "busy_timeout": "2s"
        }
    }))
    .expect("settings should deserialize");

    assert_eq!(
        settings.connection.journal_mode,
        Some(SqliteJournalMode::Wal)
    );
    assert_eq!(
        settings.connection.synchronous,
        Some(SqliteSynchronousMode::Normal)
    );
    assert_eq!(
        settings.connection.busy_timeout,
        std::time::Duration::from_secs(2)
    );
    assert!(settings.connection.foreign_keys);
    assert!(!settings.migrate_on_startup);
}

#[tokio::test]
async fn connects_to_memory_and_applies_sqlite_options() {
    let connection = SqliteConnectionSettings::new("sqlite::memory:")
        .with_journal_mode(Some(SqliteJournalMode::Memory))
        .with_synchronous(Some(SqliteSynchronousMode::Normal));
    let config = SqliteBootstrapSettings::from_connection(connection)
        .build()
        .expect("settings should be valid");
    let options = connect_options(config.connection_config())
        .expect("validated connection options should build");
    let pool = connect_pool_with_options(options, config.pool_config())
        .await
        .expect("in-memory SQLite should connect");

    let foreign_keys: i64 = sqlx::query_scalar("PRAGMA foreign_keys")
        .fetch_one(&pool)
        .await
        .expect("foreign key pragma should be readable");
    let journal_mode: String = sqlx::query_scalar("PRAGMA journal_mode")
        .fetch_one(&pool)
        .await
        .expect("journal mode should be readable");
    let synchronous: i64 = sqlx::query_scalar("PRAGMA synchronous")
        .fetch_one(&pool)
        .await
        .expect("synchronous pragma should be readable");

    assert_eq!(foreign_keys, 1);
    assert_eq!(journal_mode, "memory");
    assert_eq!(synchronous, 1);
    ping_pool(&pool).await.expect("pool should respond");
}

#[tokio::test]
async fn creates_a_missing_file_only_when_explicitly_enabled() {
    let database = TempDatabase::new();
    let connection = SqliteConnectionSettings::new(database.url()).with_create_if_missing(true);
    let config = SqliteBootstrapSettings::from_connection(connection)
        .build()
        .expect("settings should be valid");
    let pool = connect_pool(config.connection_config(), config.pool_config())
        .await
        .expect("SQLite should create the configured database file");

    assert!(database.0.is_file());
    pool.close().await;
}

#[tokio::test]
async fn bootstrap_requires_migrator_before_connecting() {
    let config = SqliteBootstrapSettings::new("sqlite::memory:")
        .with_migrate_on_startup(true)
        .build()
        .expect("settings should be valid");
    let error = bootstrap_database(config, None)
        .await
        .expect_err("missing migrator must be rejected");

    assert!(matches!(error, SqliteBootstrapError::MissingMigrator));
}

#[tokio::test]
async fn bootstrap_runs_migrations_and_returns_ready_pool() {
    let config = SqliteBootstrapSettings::new("sqlite::memory:")
        .with_migrate_on_startup(true)
        .build()
        .expect("settings should be valid");
    let pool = bootstrap_database(config, Some(&sqlx::migrate::Migrator::DEFAULT))
        .await
        .expect("SQLite bootstrap should succeed");

    let migration_table: i64 = sqlx::query_scalar(
        "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = '_sqlx_migrations'",
    )
    .fetch_one(&pool)
    .await
    .expect("migration table query should succeed");
    assert_eq!(migration_table, 1);
    assert!(check_pool_health(&pool).await.ready());
}

#[tokio::test]
async fn transaction_helpers_commit_and_rollback() {
    let config = SqliteBootstrapSettings::new("sqlite::memory:")
        .build()
        .expect("settings should be valid");
    let pool = connect_pool(config.connection_config(), config.pool_config())
        .await
        .expect("in-memory SQLite should connect");
    sqlx::query("CREATE TABLE events (id INTEGER PRIMARY KEY)")
        .execute(&pool)
        .await
        .expect("table should be created");

    let mut rolled_back = begin_transaction(&pool)
        .await
        .expect("transaction should begin");
    sqlx::query("INSERT INTO events (id) VALUES (1)")
        .execute(&mut *rolled_back)
        .await
        .expect("insert should succeed");
    rollback_transaction(rolled_back)
        .await
        .expect("rollback should succeed");

    let committed = begin_transaction(&pool)
        .await
        .expect("transaction should begin");
    commit_transaction(committed)
        .await
        .expect("commit should succeed");

    let count: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM events")
        .fetch_one(&pool)
        .await
        .expect("count should succeed");
    assert_eq!(count, 0);
}

#[tokio::test]
async fn unavailable_health_contains_only_stable_error() {
    let config = SqliteBootstrapSettings::new("sqlite::memory:")
        .build()
        .expect("settings should be valid");
    let pool = connect_pool(config.connection_config(), config.pool_config())
        .await
        .expect("in-memory SQLite should connect");
    pool.close().await;

    let health = check_pool_health(&pool).await;
    assert_eq!(health.status(), SqliteHealthStatus::Unavailable);
    assert_eq!(health.error(), Some(SQLITE_HEALTH_ERROR));
    let output = format!("{health:?}");
    assert!(output.contains("has_error"));
    assert!(!output.contains(SQLITE_HEALTH_ERROR));
}

#[test]
fn health_value_reports_ready_state() {
    let health = SqliteHealth {
        status: SqliteHealthStatus::Ready,
        latency: std::time::Duration::from_millis(1),
    };

    assert!(health.ready());
    assert_eq!(health.error(), None);
    assert_eq!(health.latency(), std::time::Duration::from_millis(1));
}

#[test]
fn diagnostics_classify_errors_without_exposing_source_details() {
    let private_detail = "/private/customer/app.db";
    let pool_error = SqlitePoolError::Sqlx(sqlx::Error::Io(std::io::Error::new(
        std::io::ErrorKind::PermissionDenied,
        private_detail,
    )));
    let diagnosis = diagnose_pool_error(SqliteOperation::Connect, &pool_error);
    let output = format!("{pool_error} {pool_error:?} {diagnosis} {diagnosis:?}");

    assert_eq!(diagnosis.kind(), SqliteDiagnosticKind::PermissionDenied);
    assert_eq!(
        diagnosis.to_diagnostic().kind(),
        DiagnosticKind::PermissionDenied
    );
    assert!(!diagnosis.retryable());
    assert!(!output.contains(private_detail));
    assert_eq!(pool_error.error_code().as_str(), "sqlite_unavailable");
}

#[test]
fn migration_diagnostics_preserve_stable_classification() {
    let error = sqlx::migrate::MigrateError::VersionMismatch(20260821000100);
    assert_eq!(
        MigrationFailureKind::from_error(&error),
        MigrationFailureKind::VersionMismatch {
            version: 20260821000100
        }
    );

    let diagnosis = diagnose_migration_error(&error);
    assert_eq!(
        diagnosis.kind(),
        SqliteDiagnosticKind::MigrationChecksumMismatch
    );
    assert!(diagnosis.message().contains("20260821000100"));
    assert_eq!(diagnosis.operation(), SqliteOperation::Migrate);
    assert!(!diagnosis.retryable());
}