footing 0.6.1

Feature-gated foundations for Rust backend services
Documentation
//! SQLite connection, bootstrap, migration, health, and transaction runtime.

use std::{
    fmt,
    str::FromStr,
    time::{Duration, Instant},
};

use sqlx::{
    ConnectOptions, Sqlite, SqlitePool, Transaction,
    migrate::Migrator,
    sqlite::{
        SqliteConnectOptions, SqliteJournalMode as SqlxJournalMode, SqlitePoolOptions,
        SqliteSynchronous as SqlxSynchronous,
    },
};

use super::{
    config::{
        SqliteBootstrapConfig, SqliteConnectionConfig, SqliteJournalMode, SqlitePoolConfig,
        SqliteSynchronousMode,
    },
    diagnostics::{
        SqliteBootstrapError, SqliteOperation, SqlitePoolError, diagnose_migration_error,
        diagnose_pool_error,
    },
};

/// Converts validated SQLite configuration into SQLx connection options.
pub fn connect_options(
    config: &SqliteConnectionConfig,
) -> Result<SqliteConnectOptions, SqlitePoolError> {
    let mut options = SqliteConnectOptions::from_str(&config.database_url)
        .map_err(SqlitePoolError::Sqlx)?
        .create_if_missing(config.create_if_missing)
        .read_only(config.read_only)
        .foreign_keys(config.foreign_keys)
        .busy_timeout(config.busy_timeout)
        .statement_cache_capacity(config.statement_cache_capacity);

    if let Some(mode) = config.journal_mode {
        options = options.journal_mode(sqlx_journal_mode(mode));
    }
    if let Some(mode) = config.synchronous {
        options = options.synchronous(sqlx_synchronous_mode(mode));
    }

    Ok(options)
}

/// Converts validated SQLite pool configuration into SQLx pool options.
#[must_use]
pub fn pool_options(config: SqlitePoolConfig) -> SqlitePoolOptions {
    SqlitePoolOptions::new()
        .max_connections(config.max_connections)
        .min_connections(config.min_connections)
        .acquire_timeout(config.acquire_timeout)
        .test_before_acquire(config.test_before_acquire)
        .idle_timeout(config.idle_timeout)
        .max_lifetime(config.max_lifetime)
}

/// Connects a SQLite pool using validated connection and pool configuration.
pub async fn connect_pool(
    connection_config: &SqliteConnectionConfig,
    pool_config: SqlitePoolConfig,
) -> Result<SqlitePool, SqlitePoolError> {
    let options = connect_options(connection_config)?;
    connect_pool_with_options(options, pool_config).await
}

/// Connects a SQLite pool using caller-supplied SQLx connection options.
///
/// This is the explicit escape hatch for advanced SQLx options such as a
/// custom VFS or immutable database access. In-memory databases and temporary
/// databases with an empty filename use one retained connection without idle
/// or age-based recycling so ordinary pool maintenance does not erase them.
/// Native `file:` URI filenames also use this retained-connection policy:
/// SQLite interprets their parameters independently of SQLx's memory flag.
/// This conservatively limits even file-backed URI pools to one connection;
/// use an ordinary filename when a persistent database needs a larger pool.
/// Filenames containing NUL bytes are rejected before connection. Native
/// `file:` URIs must also omit `%00` escapes, which SQLite silently truncates.
pub async fn connect_pool_with_options(
    connect_options: SqliteConnectOptions,
    pool_config: SqlitePoolConfig,
) -> Result<SqlitePool, SqlitePoolError> {
    database_pool_options(&connect_options, pool_config)?
        .connect_with(connect_options)
        .await
        .map_err(SqlitePoolError::Sqlx)
}

/// Creates a lazily connected SQLite pool using validated configuration.
pub fn connect_lazy_pool(
    connection_config: &SqliteConnectionConfig,
    pool_config: SqlitePoolConfig,
) -> Result<SqlitePool, SqlitePoolError> {
    let options = connect_options(connection_config)?;
    connect_lazy_pool_with_options(options, pool_config)
}

/// Creates a lazy SQLite pool using caller-supplied SQLx connection options.
///
/// This is the lazy counterpart to [`connect_pool_with_options`]. Filename
/// validation happens immediately, before a pool is returned.
pub fn connect_lazy_pool_with_options(
    connect_options: SqliteConnectOptions,
    pool_config: SqlitePoolConfig,
) -> Result<SqlitePool, SqlitePoolError> {
    Ok(database_pool_options(&connect_options, pool_config)?.connect_lazy_with(connect_options))
}

fn database_pool_options(
    options: &SqliteConnectOptions,
    config: SqlitePoolConfig,
) -> Result<SqlitePoolOptions, SqlitePoolError> {
    let filename = options.get_filename().as_os_str().as_encoded_bytes();
    if filename.contains(&0)
        || (filename.starts_with(b"file:") && filename.windows(3).any(|part| part == b"%00"))
    {
        return Err(SqlitePoolError::Sqlx(sqlx::Error::Configuration(
            "SQLite filename must not contain NUL bytes or native URI %00 escapes".into(),
        )));
    }
    // Empty filenames are temporary; native URI parameters can also select a
    // private memory database without setting SQLx's in_memory flag. Retain a
    // single connection for opaque URIs instead of duplicating SQLite's parser.
    let transient = filename.is_empty()
        || filename == b":memory:"
        || filename.starts_with(b"file:")
        || options
            // SQLx exposes the memory flag through the URL, but its generated
            // `file:sqlx-in-memory-*` filenames cannot be encoded as URL hosts.
            // Inspect a copy with a plain filename, preserving every flag.
            .clone()
            .filename("database")
            .to_url_lossy()
            .query_pairs()
            .any(|(key, value)| key == "mode" && value == "memory");
    let pool = pool_options(config);
    Ok(if transient {
        pool.max_connections(1)
            .min_connections(1)
            .idle_timeout(None)
            .max_lifetime(None)
            // Avoid yielding after removing the sole connection from the pool:
            // cancellation during an acquire must not discard the database.
            .test_before_acquire(false)
    } else {
        pool
    })
}

/// Creates, connects, and optionally migrates a SQLite database.
///
/// SQLite has no process-wide SQLx migration lock. Applications running more
/// than one process must elect a single startup migrator before serving traffic.
pub async fn bootstrap_database(
    config: SqliteBootstrapConfig,
    migrator: Option<&Migrator>,
) -> Result<SqlitePool, SqliteBootstrapError> {
    let migrator = if config.migrate_on_startup {
        Some(migrator.ok_or(SqliteBootstrapError::MissingMigrator)?)
    } else {
        None
    };

    let pool = connect_pool(&config.connection_config, config.pool_config)
        .await
        .map_err(|source| SqliteBootstrapError::Connect {
            diagnosis: diagnose_pool_error(SqliteOperation::Connect, &source),
            source: Box::new(source),
        })?;

    if let Some(migrator) = migrator {
        tracing::info!("running SQLite database migrations");
        migrator
            .run(&pool)
            .await
            .map_err(|source| SqliteBootstrapError::Migration {
                diagnosis: diagnose_migration_error(&source),
                source: Box::new(source),
            })?;
    }

    Ok(pool)
}

/// Verifies that a SQLite pool can execute a simple query.
pub async fn ping_pool(pool: &SqlitePool) -> Result<(), sqlx::Error> {
    sqlx::query("SELECT 1").execute(pool).await?;
    Ok(())
}

/// Checks pool connectivity and returns a redacted health result.
pub async fn check_pool_health(pool: &SqlitePool) -> SqliteHealth {
    let started = Instant::now();
    match ping_pool(pool).await {
        Ok(()) => SqliteHealth {
            status: SqliteHealthStatus::Ready,
            latency: started.elapsed(),
        },
        Err(_) => SqliteHealth {
            status: SqliteHealthStatus::Unavailable,
            latency: started.elapsed(),
        },
    }
}

pub(super) const SQLITE_HEALTH_ERROR: &str = "database health check failed";

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
/// Status of SQLite health.
pub enum SqliteHealthStatus {
    /// The database is reachable.
    Ready,
    /// The database is unavailable.
    Unavailable,
}

#[derive(Clone, PartialEq, Eq)]
#[non_exhaustive]
/// Redacted SQLite health result.
pub struct SqliteHealth {
    pub(super) status: SqliteHealthStatus,
    pub(super) latency: Duration,
}

impl fmt::Debug for SqliteHealth {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("SqliteHealth")
            .field("status", &self.status)
            .field("latency", &self.latency)
            .field("has_error", &!self.ready())
            .finish()
    }
}

impl SqliteHealth {
    #[must_use]
    /// Returns the health status.
    pub const fn status(&self) -> SqliteHealthStatus {
        self.status
    }

    #[must_use]
    /// Returns the health check latency.
    pub const fn latency(&self) -> Duration {
        self.latency
    }

    #[must_use]
    /// Returns a stable redacted error summary when unavailable.
    pub fn error(&self) -> Option<&str> {
        (!self.ready()).then_some(SQLITE_HEALTH_ERROR)
    }

    #[must_use]
    /// Returns whether the database is ready.
    pub const fn ready(&self) -> bool {
        matches!(self.status, SqliteHealthStatus::Ready)
    }
}

/// SQLx transaction specialized for SQLite.
pub type SqliteTransaction<'a> = Transaction<'a, Sqlite>;

const fn sqlx_journal_mode(mode: SqliteJournalMode) -> SqlxJournalMode {
    match mode {
        SqliteJournalMode::Delete => SqlxJournalMode::Delete,
        SqliteJournalMode::Truncate => SqlxJournalMode::Truncate,
        SqliteJournalMode::Persist => SqlxJournalMode::Persist,
        SqliteJournalMode::Memory => SqlxJournalMode::Memory,
        SqliteJournalMode::Wal => SqlxJournalMode::Wal,
        SqliteJournalMode::Off => SqlxJournalMode::Off,
    }
}

const fn sqlx_synchronous_mode(mode: SqliteSynchronousMode) -> SqlxSynchronous {
    match mode {
        SqliteSynchronousMode::Off => SqlxSynchronous::Off,
        SqliteSynchronousMode::Normal => SqlxSynchronous::Normal,
        SqliteSynchronousMode::Full => SqlxSynchronous::Full,
        SqliteSynchronousMode::Extra => SqlxSynchronous::Extra,
    }
}