claw-core 0.1.2

Embedded local database engine for ClawDB — an agent-native cognitive database
Documentation
//! WAL configuration helpers for claw-core.
//!
//! This module provides convenience functions for inspecting and tuning the
//! SQLite Write-Ahead Log (WAL) on an open connection pool. The WAL is
//! SQLite's high-concurrency journaling mode and is the recommended default
//! for claw-core deployments.

use sqlx::SqlitePool;

use crate::error::ClawResult;

/// Apply WAL journal mode and set the WAL auto-checkpoint threshold.
///
/// This is equivalent to executing:
///
/// ```sql
/// PRAGMA journal_mode = WAL;
/// PRAGMA wal_autocheckpoint = <checkpoint_pages>;
/// ```
///
/// # Errors
///
/// Returns a [`crate::error::ClawError`] if either PRAGMA fails.
pub async fn configure_wal(pool: &SqlitePool, checkpoint_pages: u32) -> ClawResult<()> {
    sqlx::query("PRAGMA journal_mode = WAL")
        .execute(pool)
        .await?;

    sqlx::query(&format!("PRAGMA wal_autocheckpoint = {checkpoint_pages}"))
        .execute(pool)
        .await?;

    tracing::debug!(checkpoint_pages, "WAL configured");
    Ok(())
}

/// Trigger an immediate WAL checkpoint, flushing WAL frames into the main
/// database file.
///
/// # Errors
///
/// Returns a [`crate::error::ClawError`] if the checkpoint PRAGMA fails.
pub async fn checkpoint(pool: &SqlitePool) -> ClawResult<()> {
    sqlx::query("PRAGMA wal_checkpoint(PASSIVE)")
        .execute(pool)
        .await?;

    tracing::debug!("WAL checkpoint completed");
    Ok(())
}

/// Return the current journal mode string for the database.
///
/// # Errors
///
/// Returns a [`crate::error::ClawError`] if the PRAGMA query fails.
pub async fn journal_mode(pool: &SqlitePool) -> ClawResult<String> {
    let row: (String,) = sqlx::query_as("PRAGMA journal_mode")
        .fetch_one(pool)
        .await?;
    Ok(row.0)
}

/// The WAL checkpoint mode.
///
/// # Example
///
/// ```rust
/// use claw_core::CheckpointMode;
/// assert_eq!(CheckpointMode::Passive.as_str(), "PASSIVE");
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CheckpointMode {
    /// Checkpoint as many frames as possible without waiting for readers.
    Passive,
    /// Wait for readers to finish, then checkpoint everything.
    Full,
    /// Like [`CheckpointMode::Full`] but also resets the WAL frame counter.
    Restart,
    /// Like [`CheckpointMode::Restart`] but also truncates the WAL file.
    Truncate,
}

impl CheckpointMode {
    /// Return the PRAGMA argument string for this mode.
    ///
    /// # Example
    ///
    /// ```rust
    /// use claw_core::CheckpointMode;
    /// assert_eq!(CheckpointMode::Full.as_str(), "FULL");
    /// ```
    pub fn as_str(self) -> &'static str {
        match self {
            CheckpointMode::Passive => "PASSIVE",
            CheckpointMode::Full => "FULL",
            CheckpointMode::Restart => "RESTART",
            CheckpointMode::Truncate => "TRUNCATE",
        }
    }
}

/// The result of a WAL checkpoint operation.
///
/// Returned by checkpoint helpers to report success or failure details.
#[derive(Debug, Clone)]
pub struct CheckpointResult {
    /// The checkpoint mode that was used.
    pub mode: CheckpointMode,
    /// Whether the checkpoint completed successfully.
    pub success: bool,
}